I also select the a tag and its child elements here.
What is the difference between these two? How to write the following for statement so that no error is reported
<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>
The selector can only use the children method. If you want to use children(), you can only change navs[i] to navs.eq(i)
$(navs[i]).children('.pic').attr("src",nav_pic_on[i])
Don’t use nav[i], use nav.eq(i)