Get clicked element in delegated event with jQuery

徘徊边缘 提交于 2019-11-27 22:47:51

问题


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.


回答1:


You need to use .on() to delegate events. As the documentation says:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector.

So it should be:

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

Your use of .click('.child', function...) does not do delegation. It matches the function signature:

.click(eventData, handler)

described here. So it's just binding to the parent, not delegating to the child, that's why you get the wrong value in this.




回答2:


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



来源:https://stackoverflow.com/questions/26657058/get-clicked-element-in-delegated-event-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!