简体   繁体   中英

Use jQuery .click() function with an individual element

I want to show the list of tags on an Tumblr blog only when the user clicks on the tags button. For that I use this HTML and jQuery.

HTML

  <span class="tags-link">Tags</span>
  <ul class="tags">
    <li> <a href="{TagURL}">{Tag}</a> </li>
  </ul>

jQuery

$(document).ready(function(){
    $(".tags-link").click(function() {
        $(".tags").slideDown(700, function(){
            //end animation
        });
    });
});

Every time I click on the .tags-link every .tags shows up on the page, and I only want the ones of the post where the user has clicked to be shown. I recently started learning jQuery and I'm a little lost here...

你可以使用.next() http://api.jquery.com/next/

$(this).next(".tags").slideDown(700, function(){

You need to target the tags that is the next adjacent element only:

$(document).ready(function(){
    $(".tags-link").click(function() {
        $(this).next(".tags").slideDown(700, function(){
            //end animation
        });
    });
});

You can set a data attribute on both the span with class "tags-link" and the ul with class "tags". Then when you click the ".tags-link" element, it will show the ".tags" element with the same data attribute.

For example:

HTML

<span class="tags-link" data-id="1">Tags</span>
<ul class="tags" data-id="1">
  <li> <a href="{TagURL}">{Tag}</a> </li>
</ul>

jQuery

$(document).ready(function(){
    $(".tags-link").click(function() {
        var id = $(this).attr('data-id');
        $(".tags[data-id='" + id + "']").slideDown(700, function(){
            //end animation
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM