开发者

jQuery targeting specific links in an optimal way

开发者 https://www.devze.com 2023-02-09 08:18 出处:网络
Note: This is m开发者_开发知识库ore of a best how rather than how question. I have several links within a ul that I would like to target but not every single a tag.While I know I can target each elem

Note: This is m开发者_开发知识库ore of a best how rather than how question.

I have several links within a ul that I would like to target but not every single a tag. While I know I can target each element by ID I would like to know what is best practice (most optimized selceting, smallest amount of code) for this task.

   $("#id").find("a").click(function(){
  //run function                    
});     

markup:

    <nav id="id">    
  <ul>
    <li id="want-01"><a href="#">link</a></li>
    <li id="want-02"><a href="#">link</a></li>
    <li id="want-03"><a href="#">link</a></li>
    <li id="dont-want-01"><a href="#">link</a></li>
    <li id="dont-want-02"><a href="#">link</a></li>
    <li id="want-04"><a href="#">link</a></li>
    <li id="want-05"><a href="#">link</a></li>
  </ul>       
</nav>


The use of a class would seem appropriate here. Create a new class say 'li_link' and add it to the li elements that you want to link to. Then apply your click handler to all li elments with the class, eg.

$('.li_link').click(function() {...});

If you want to change the li elements that are handled dynamically, you could consider using live events. This allows you to add and remove the 'li_link' class from li elements and the click handler will apply or stop being applied to the li elements automatically.

To set up a live event use something like this:

 $('.li_link').live('click', function() {...});


$("#id").find("a").not("#dont-want-01 a, #dont-want-02 a").click(function(){   

});   


Theres' really no way to do it with that HTML, but if you implmented a rel attr or class you can select it fairly easily.

   <nav id="id">    
  <ul>
    <li id="want-01" rel="wanted"><a href="#">link</a></li>
    <li id="want-02" rel="wanted"><a href="#">link</a></li>
    <li id="want-03" rel="wanted"><a href="#">link</a></li>
    <li id="dont-want-01"><a href="#">link</a></li>
    <li id="dont-want-02"><a href="#">link</a></li>
    <li id="want-04" rel="wanted"> <a href="#">link</a></li>
    <li id="want-05" rel="wanted"><a href="#">link</a></li>
  </ul>       
</nav>

$("#id").find('li[rel=wanted]').children();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号