简体   繁体   English

将元素添加到DOM后,jQuery.click无法正常工作

[英]jQuery.click not working after adding element to the DOM

I have a simple jQuery('div#star').click(function. 我有一个简单的jQuery('div#star')。点击(功能。

The function works once when the DOM is initially loaded, but at a later time, I add a div#star to the DOM, and at that point the click function is not working. 最初加载DOM时,该函数会运行一次,但稍后我会在DOM中添加div#star,此时click函数不起作用。

I am using jQuery 1.4.4, and as far as I know, I shouldn't need to use .live or .bind anymore. 我正在使用jQuery 1.4.4,据我所知,我不再需要使用.live或.bind了。 There is never more than one div#star in the DOM at any one time. DOM中任何时候都不会有多个div#star。 I tried changing from id="star" to class="star" but that didn't help. 我尝试从id =“star”更改为class =“star”,但这没有帮助。

Any suggestions on how to get this working or why it isn't working? 关于如何使这个工作或为什么它不工作的任何建议?

I've had the .click inside the jQuery(document).ready, and in an external js file, and neither works after adding the div to the DOM. 我在jQuery(文档).ready中有.click,并且在外部js文件中,并且在将div添加到DOM之后都不起作用。

This works with jQuery 2.0.3 这适用于jQuery 2.0.3

$(document).on('click', '#myDiv', function() {
    myFunc();
});

As of jQuery 1.7, the .live() method is deprecated. 从jQuery 1.7开始,不推荐使用.live()方法。 The current recommendation is to use .on() which provides all functionality covering the previous methods of attaching event handlers. 目前的建议是使用.on() ,它提供了覆盖事先处理程序的先前方法的所有功能。 Simply put, you don't have to decide any more since on() does it all. 简而言之,您不必再决定,因为on()可以做到这一切。

Documentation is handily provided in the help for converting from the older jQuery event methods .bind() , .delegate() , and .live() 帮助中提供了文档,用于转换旧的jQuery事件方法.bind() ,. delegate().live()

You still need to use live events. 您仍然需要使用直播活动。

http://api.jquery.com/live/ http://api.jquery.com/live/

尝试
.on('event', 'element', function(){ //code })

You need to use either live or delegate here. 你需要在这里使用livedelegate Nothing has changed in this department since jQuery 1.4.4. 自jQuery 1.4.4以来,这个部门没有任何变化。

Try to think of it like this: click and bind attach an event to the element itself, so when the element disappears, all the information about the event does too. 试着这样想: clickbind将事件附加到元素本身,所以当元素消失时,关于事件的所有信息也会这样做。 live attaches the event at the document level and it includes information about which element and event type to listen for. live在文档级别附加事件,它包含有关要侦听的元素和事件类型的信息。 delegate does the same thing, except it attaches the event information to whatever parent element you like. delegate做同样的事情,除了它将事件信息附加到你喜欢的任何父元素。

You can use delegate instead on : 您可以使用委托来代替:

$(document).delegate('click', "selector", function() {
    //your code
});

I hope it will help. 我希望它会有所帮助。

user "live" method $("div#star").live("click", function() {}); 用户“直播”方法$("div#star").live("click", function() {});

Doc 文件

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

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