jQuery单击不为动态创建的项目工作[复制]

时间:2022-10-22 07:34:50

This question already has an answer here:

这个问题已经有了答案:

I have a piece of jQuery that loops through each element in a given div( #container) and does a javascript alert each time a span is clicked. This works fine if the <span>'s are static.

我有一段jQuery,它循环遍历给定div(#container)中的每个元素,并在每次单击span时发出javascript警报。如果's是静态的,那么这样做很有效。

However, if I use a piece of code like:

但是,如果我使用一段代码,比如:

$(someLink).click(function(){
   $("#container").html( <new html with new spans> )
});

The jQuery code doesn't fire off. Oddly enough though

jQuery代码没有启动,但奇怪的是

My question is : Is there a reason my Click events don't work for dynamically created items? I assume I will have to add something into my document ready or heartbeat-script (which is fired every 100 miliseconds) to hook up the events??

我的问题是:有什么原因导致我的单击事件不能用于动态创建的项目?我假设我必须在我的文档中添加一些东西(每100毫秒触发一次)来连接事件?

8 个解决方案

#1


110  

Do this:

这样做:

 $( '#wrapper' ).on( 'click', 'a', function () { ... });

where #wrapper is a static element in which you add the dynamic links.

其中#包装器是一个静态元素,您可以在其中添加动态链接。

So, you have a wrapper which is hard-coded into the HTML source code:

因此,您有一个硬编码到HTML源代码中的包装器:

<div id="wrapper"></div>

and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.

你用动态内容填充它。其思想是将事件委托给该包装器,而不是直接将处理程序绑定到动态元素上。


Btw, I recommend Backbone.js - it gives structure to this process:

顺便说一句,我建议骨干。js -为这个过程提供了结构:

var YourThing = Backbone.View.extend({

    // the static wrapper (the root for event delegation)
    el: $( '#wrapper' ),

    // event bindings are defined here 
    events: {
        'click a': 'anchorClicked'
    },

    // your DOM event handlers
    anchorClicked: function () {
        // handle click event 
    }

});

new YourThing; // initializing your thing

#2


63  

source: this post

这篇文章来源:

if you created your elements dynamically(using javascript), then this code doesn't work. Because, .click() will attach events to elements that already exists. As you are dynamically creating your elements using javascript, it doesn't work.

如果您动态地创建了元素(使用javascript),那么这个代码就不起作用了。因为,.click()将把事件附加到已经存在的元素上。由于您正在使用javascript动态创建元素,所以它不能工作。

For this you have to use some other functions which works on dynamically created elements. This can be done in different ways..

为此,您必须使用一些其他功能,这些函数可以动态创建元素。这可以通过不同的方式来实现。

Earlier we have .live() function

前面我们有。live()函数

$('selector').live('click', function()
{
//your code
});

but .live() is deprecated.This can be replaced by other functions.

但是.live()是弃用。这可以被其他函数代替。

Delegate():

委托():

Using delegate() function you can click on dynamically generated HTML elements.

使用delegate()函数可以单击动态生成的HTML元素。

Example:

例子:

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

ON():

在():

Using on() function you can click on dynamically generated HTML elements.

使用on()函数,可以单击动态生成的HTML元素。

Example:

例子:

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

#3


4  

Try something like

试着像

$("#container").on('click', 'someLinkSelector', function(){ $("#container").html( <new html with new spans> ) });

You basically need to attach your events from a non-dynamic part of the DOM so it can watch for dynamically-created elements.

您基本上需要从DOM的非动态部分附加事件,以便它可以监视动态创建的元素。

#4


3  

$("#container").delegate("span", "click", function (){
    alert(11);
});

#5


1  

Using .click will only attach events to elements that already exist.

使用。click只会将事件附加到已经存在的元素上。

You need to use a function which monitors for dynamically created events - in older versions of JQuery this was .live(), but this has been superceded by .on()

您需要使用一个函数来监视动态创建的事件——在旧版本的JQuery中,这个函数是.live(),但是它已经被.on()取代了

#6


0  

Use the new jQuery on function in 1.7.1 -

在1.7.1中使用新的jQuery函数。

http://api.jquery.com/on/

http://api.jquery.com/on/

#7


0  

I faced this problem a few days ago - the solution for me was to use .bind() to bind the required function to the dynamically created link.

几天前我遇到了这个问题——我的解决方案是使用.bind()将所需的函数绑定到动态创建的链接。

var catLink = $('<a href="#" id="' + i + '" class="lnkCat">' + category.category + '</a>');
catLink.bind("click", function(){
 $.categories.getSubCategories(this);
});

getSubCategories : function(obj) {
 //do something
}

I hope this helps.

我希望这可以帮助。

#8


0  

You have to add click event to an exist element. You can not add event to dom elements dynamic created. I you want to add event to them, you should bind event to an existed element using ".on".

您必须向exist元素添加单击事件。不能将事件添加到动态创建的dom元素中。我希望向它们添加事件,应该使用“.on”将事件绑定到已存在的元素。

$('p').on('click','selector_you_dynamic_created',function(){...});

.delegate should work,too.

.delegate也应该工作,。

#1


110  

Do this:

这样做:

 $( '#wrapper' ).on( 'click', 'a', function () { ... });

where #wrapper is a static element in which you add the dynamic links.

其中#包装器是一个静态元素,您可以在其中添加动态链接。

So, you have a wrapper which is hard-coded into the HTML source code:

因此,您有一个硬编码到HTML源代码中的包装器:

<div id="wrapper"></div>

and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.

你用动态内容填充它。其思想是将事件委托给该包装器,而不是直接将处理程序绑定到动态元素上。


Btw, I recommend Backbone.js - it gives structure to this process:

顺便说一句,我建议骨干。js -为这个过程提供了结构:

var YourThing = Backbone.View.extend({

    // the static wrapper (the root for event delegation)
    el: $( '#wrapper' ),

    // event bindings are defined here 
    events: {
        'click a': 'anchorClicked'
    },

    // your DOM event handlers
    anchorClicked: function () {
        // handle click event 
    }

});

new YourThing; // initializing your thing

#2


63  

source: this post

这篇文章来源:

if you created your elements dynamically(using javascript), then this code doesn't work. Because, .click() will attach events to elements that already exists. As you are dynamically creating your elements using javascript, it doesn't work.

如果您动态地创建了元素(使用javascript),那么这个代码就不起作用了。因为,.click()将把事件附加到已经存在的元素上。由于您正在使用javascript动态创建元素,所以它不能工作。

For this you have to use some other functions which works on dynamically created elements. This can be done in different ways..

为此,您必须使用一些其他功能,这些函数可以动态创建元素。这可以通过不同的方式来实现。

Earlier we have .live() function

前面我们有。live()函数

$('selector').live('click', function()
{
//your code
});

but .live() is deprecated.This can be replaced by other functions.

但是.live()是弃用。这可以被其他函数代替。

Delegate():

委托():

Using delegate() function you can click on dynamically generated HTML elements.

使用delegate()函数可以单击动态生成的HTML元素。

Example:

例子:

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

ON():

在():

Using on() function you can click on dynamically generated HTML elements.

使用on()函数,可以单击动态生成的HTML元素。

Example:

例子:

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

#3


4  

Try something like

试着像

$("#container").on('click', 'someLinkSelector', function(){ $("#container").html( <new html with new spans> ) });

You basically need to attach your events from a non-dynamic part of the DOM so it can watch for dynamically-created elements.

您基本上需要从DOM的非动态部分附加事件,以便它可以监视动态创建的元素。

#4


3  

$("#container").delegate("span", "click", function (){
    alert(11);
});

#5


1  

Using .click will only attach events to elements that already exist.

使用。click只会将事件附加到已经存在的元素上。

You need to use a function which monitors for dynamically created events - in older versions of JQuery this was .live(), but this has been superceded by .on()

您需要使用一个函数来监视动态创建的事件——在旧版本的JQuery中,这个函数是.live(),但是它已经被.on()取代了

#6


0  

Use the new jQuery on function in 1.7.1 -

在1.7.1中使用新的jQuery函数。

http://api.jquery.com/on/

http://api.jquery.com/on/

#7


0  

I faced this problem a few days ago - the solution for me was to use .bind() to bind the required function to the dynamically created link.

几天前我遇到了这个问题——我的解决方案是使用.bind()将所需的函数绑定到动态创建的链接。

var catLink = $('<a href="#" id="' + i + '" class="lnkCat">' + category.category + '</a>');
catLink.bind("click", function(){
 $.categories.getSubCategories(this);
});

getSubCategories : function(obj) {
 //do something
}

I hope this helps.

我希望这可以帮助。

#8


0  

You have to add click event to an exist element. You can not add event to dom elements dynamic created. I you want to add event to them, you should bind event to an existed element using ".on".

您必须向exist元素添加单击事件。不能将事件添加到动态创建的dom元素中。我希望向它们添加事件,应该使用“.on”将事件绑定到已存在的元素。

$('p').on('click','selector_you_dynamic_created',function(){...});

.delegate should work,too.

.delegate也应该工作,。