我这里同样的选择a 标签和他的子元素。
求问这2者有什么区别,下面的for语句怎么写才能不报错
<p class="topbox" id="topbox">
<a class="nav-on" href="/waihui/">
<img class="pic" src="/image/menu9-1.jpg" alt="外汇品种"></a>
<a href="/guijinshu/">
<img class="pic" src="/image/menu10.jpg" alt="贵金属">
</a>
<a href="/yuanyou/">
<img class="pic" src="/image/menu11.jpg" alt="原油">
</a>
<a href="/qihuoheyue/">
<img class="pic" src="/image/menu12.jpg" alt="期货合约">
</a>
<a href="/meigu/">
<img class="pic" src="/image/menu13.jpg" alt="美股">
</a>
</p>
<script>
var navs = $('#topbox a');
var pic = $('#topbox .pic');
var nav_pic_on = ['/image/menu9-1.jpg','/image/menu10-1.jpg','/image/menu11-1.jpg','/image/menu12-1.jpg','/image/menu13-1.jpg'];
$('#topbox a').each(function(i){
if($(this).hasClass('nav-on')){
console.log($(this));
$(this).children('.pic').attr("src",nav_pic_on[i]);
}
})
for(i=0;i<navs.length;i++){
if(navs[i].className=='nav-on'){
console.log(navs[i]);
navs[i].children('.pic').attr("src",nav_pic_on[i]); //报错 Uncaught TypeError: navs[i].children is not a function
}
}
</script>
选择器才能用children这个方法的,你要用children()的话,只能把navs[i]改为navs.eq(i)才行的
$(navs[i]).children('.pic').attr("src",nav_pic_on[i])
不要用 nav[i], 用nav.eq(i)