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

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - Get clicked element in delegated event with jQuery

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

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

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...