Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have some elements that I add to the DOM after the page has been loaded. And I'd like to perform some actions when I click on them. I'm using the delegation with jQuery but I don't know how to get the clicked element when I'm in the fonction ($(this) refers in this case to the parent)

<div id="parent">
    <div class="child">
        <div class="hidden"></div>
    </div>
    <div class="child">
        <div class="hidden"></div>
    </div>
</div>

<script>
$('#parent').click('.child', function(){
    $(this).find('.child').toggleClass("hidden displayed")
});
</script>

Let's say I want to toggle the inner div from "hidden" to "displayed" when I click on the "child" div. Currently when I click on the first "child" div, the two "hidden" div will be toggled, and I want to be toggled only the one in the div I clicked.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
257 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use e.target to find out which element the event originated on.

$('#parent').on('click', '.child', function(e){
    $(e.target).toggleClass("hidden displayed")
});

I also fixed the code a bit - you need to use .on for delegated events. (Mentioned by Barmar.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...