使用jQuery获取委派事件中的clicked元素 [英] Get clicked element in delegated event with jQuery

查看:150
本文介绍了使用jQuery获取委派事件中的clicked元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些元素,我在加载页面后添加到DOM。当我点击它们时,我想执行一些操作。我正在使用带有jQuery的委托,但我不知道如何获得点击的元素当我处于功能时($(this)在这种情况下指的是父母)

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>

我想说当我点击时我想将内部div从隐藏切换到显示 孩子div。目前,当我点击第一个子div时,两个隐藏div将被切换,我想只切换我点击的div中的那个。

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.

推荐答案

您需要使用 .on()来委派事件。正如文档所述:

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


当jQuery调用处理程序时, this 关键字是对传递事件的元素的引用;对于直接绑定事件,这是附加事件的元素,对于委托事件,这是一个匹配 selector 的元素。

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.

所以它应该是:

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

您使用 .click('。child',function ...)不会进行委派。函数签名:

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.

这篇关于使用jQuery获取委派事件中的clicked元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆