search

Home  >  Q&A  >  body text

javascript - jq selects the same node, 2 results are different

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>

伊谢尔伦伊谢尔伦2811 days ago563

reply all(3)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:38:27

    The selector can only use the children method. If you want to use children(), you can only change navs[i] to navs.eq(i)

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:38:27

    $(navs[i]).children('.pic').attr("src",nav_pic_on[i])

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:38:27

    Don’t use nav[i], use nav.eq(i)

    reply
    0
  • Cancelreply