简体   繁体   English

jQuery使用$ .on添加dom元素?

[英]jquery using $.on for added dom elements?

I am a bit confused, I have a bunch of elements that get added via jquery using a ajax call and I want to attach a click handler to them (there could be a lot). 我有点困惑,我使用ajax调用通过jquery添加了一堆元素,并且我想向它们附加点击处理程序(可能有很多)。

But I have no idea how to even begin this, I looked at .on and it is really confusing. 但是我什至不知道如何开始,我看着.on真的很混乱。 I want to attach a click event handler for a certain class so that when I click on it, I get the this.id and then do stuff with it. 我想为某个类附加一个click事件处理程序,以便在单击它时获得this.id ,然后对其进行处理。

What you're trying to do is called event delegation. 您尝试做的事情称为事件委托。

You want to set the event listener on a higher element in the DOM that'll never change, but only fire off the event handler if the child element that has been clicked matches a specific selector. 您想在DOM中不会更改的较高元素上设置事件侦听器,而仅在已单击的子元素与特定选择器匹配时才触发事件处理程序。

Here's how it's done with jQuery's .on() : 这是使用jQuery的.on()

$(document).on('click', '.your-selector', function(){
    alert(this.id);
});

PS You could probably apply the event listener to an element lower down in the DOM tree... PS您可能可以将事件侦听器应用于DOM树中较低的元素...

This will get you the id of a clicked element with the class "test"... 这将为您获得带有“测试”类的单击元素的ID。

$(".test").on("click", function() {
    var id = $(this).attr("id")
});

You'll need to run that after the ajax call returns. 您需要在ajax调用返回运行它。 It will only bind the click event to elements that exist when it runs, so it's no good at document.ready. 它只会将click事件绑定到运行时存在的元素,因此对document.ready不利。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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