jQuery 单击事件对动态生成的元素不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6658752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:11:46  来源:igfitidea点击:

Click event doesn't work on dynamically generated elements

jqueryevents

提问by cheng

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">

        $(document).ready(function() {

            $("button").click(function() {
                $("h2").html("<p class='test'>click me</p>")
            });   

            $(".test").click(function(){
                alert();
            });
        });

    </script>
</head>
<body>
    <h2></h2>
    <button>generate new element</button>
</body>
</html>

I was trying to generate a new tag with class name testin the <h2>by clicking the button. I also defined a click event associated with test. But the event doesn't work.

我试图生成类名称的新标签test<h2>单击按钮。我还定义了一个与test. 但该事件不起作用。

Can anyone help?

任何人都可以帮忙吗?

回答by C???

The click()binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().

click()您使用的绑定称为“直接”绑定,它只会将处理程序附加到已存在的元素。它不会绑定到将来创建的元素。为此,您必须使用on().

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

委托事件的优点是它们可以处理来自稍后添加到文档的后代元素的事件。

Source

来源

Here's what you're looking for:

这就是你要找的:

var counter = 0;

$("button").click(function() {
    $("h2").append("<p class='test'>click me " + (++counter) + "</p>")
});

// With on():

$("h2").on("click", "p.test", function(){
    alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h2></h2>
<button>generate new element</button>

The above works for those using jQuery version 1.7+. If you're using an older version, refer to the previous answer below.

以上适用于使用 jQuery 1.7+ 版本的用户。如果您使用的是旧版本,请参阅下面的上一个答案。



Previous Answer:

上一个答案

Try using live():

尝试使用live()

$("button").click(function(){
    $("h2").html("<p class='test'>click me</p>")
});   


$(".test").live('click', function(){
    alert('you clicked me!');
});

Worked for me. Tried itwith jsFiddle.

为我工作。用jsFiddle了一下。

Or there's a new-fangled way of doing it with delegate():

或者有一种新奇的方法delegate()

$("h2").delegate("p", "click", function(){
    alert('you clicked me again!');
});

An updated jsFiddle.

更新的 jsFiddle

回答by Roko C. Buljan

Use the .on()method with delegated events

.on()方法与委托事件一起使用

$('#staticParent').on('click', '.dynamicElement', function() {
    // Do something on an existent or future .dynamicElement
});

The .on()method allows you to delegate any desired event handler to:
currentelements or futureelements added to the DOM at a later time.

.on()方法允许您将任何所需的事件处理程序委托给:
当前元素或 稍后添加到 DOM 的未来元素。

P.S: Don't use .live()! From jQuery 1.7+ the .live()method is deprecated.

PS:不要用.live()!从 jQuery 1.7+ 开始,该.live()方法已被弃用。

回答by Prabhagaran

Reason:

原因:

In jQuery, Click() event binds the element only if the particular element exists in the Html code(after page loads).

在 jQuery 中,仅当特定元素存在于 Html 代码中时(页面加载后),Click() 事件才会绑定元素。

It won't consider the future elements which are created dynamically(Future element). Dynamic elements are created with the help of javascript or jquery(not in Html).

它不会考虑动态创建的未来元素(未来元素)。动态元素是在javascript 或 jquery(not in Html)的帮助下创建的。

So the normal click event won't fire on the dynamic element.

所以正常的点击事件不会在动态元素上触发。

Solution :

解决方案 :

To overcome this we should use on()function.

为了克服这个问题,我们应该使用on()函数。

delegate(),live() and on()functions have the advantages over the DOM elements.

delegate()、live() 和on()函数比 DOM 元素有优势。

delegate() and live()are deprecated(Don't use these).

不推荐使用delegate() 和 live()(不要使用这些)。

oncan only trigger both the existing and future elements.

on只能同时触发现有元素和未来元素。

oncan consider all the elements which are present on the whole page.

on可以考虑整个页面上存在的所有元素。

You should use onfunction to trigger the event on dynamically(future) created elements.

您应该使用on函数在动态(未来)创建的元素上触发事件。

Remove the code from $(document).ready:

从 $(document).ready 中删除代码:

$(".test").click(function(){

  alert();

});

Change into:

变成:

$(document).on('click','.test',function(){

  alert('Clicked');

});

回答by Abhishek

Add this function in your js file.It will work on every browser

在你的 js 文件中添加这个函数。它适用于所有浏览器

$(function() {
    $(document).on("click", '#mydiv', function() {
        alert("You have just clicked on ");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='mydiv'>Div</div>

回答by qwertymk

Change

改变

 $(".test").click(function(){

To

 $(".test").live('click', function(){

LIVE DEMO

现场演示

jQuery .live()

jQuery .live()

回答by amurra

You need to use .livefor this to work:

您需要使用.live才能工作:

$(".test").live("click", function(){
   alert();
});

or if you're using jquery 1.7+ use .on:

或者,如果您使用的是 jquery 1.7+,请使用.on

$(".test").on("click", "p", function(){
   alert();
});

回答by DSKrepps

Try .live()or .delegate()

尝试.live().delegate()

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

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

http://api.jquery.com/delegate/

http://api.jquery.com/delegate/

Your .testelement was added after the .click()method, so it didn't have the event attached to it. Live and Delegate give that event trigger to parent elements which check their children, so anything added afterwards still works. I think Live will check the entire document body, while Delegate can be given to an element, so Delegate is more efficient.

您的.test元素是在.click()方法之后添加的,因此它没有附加事件。Live 和 Delegate 将该事件触发给检查其子元素的父元素,因此之后添加的任何内容仍然有效。我认为Live会检查整个文档体,而Delegate可以赋予一个元素,因此Delegate效率更高。

More info:

更多信息:

http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/

http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/

回答by user3425150

I found two solutions at the jQuery's documentation:

我在 jQuery 的文档中找到了两个解决方案:

First: Use delegate on Body or Document

第一:在正文或文档上使用委托

E.g:

例如:

 $("body").delegate('.test', 'click', function(){
 ...
  alert('test');
 });

Why?

为什么?

Answer:Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. link: http://api.jquery.com/delegate/

回答:根据一组特定的根元素,将处理程序附加到与选择器匹配的所有元素的一个或多个事件,无论是现在还是将来。链接:http: //api.jquery.com/delegate/

Second: Put the your function at the "$( document )", using "on"and attach it to the element that you want to trigger this. The first parameter is the "event handler", the second: the element and the third: the function. E.g:

第二:将您的函数放在"$( document )",使用"on"并将其附加到要触发它的元素上。第一个参数是“事件处理程序”,第二个:元素,第三个:函数。例如:

 $( document ).on( 'click', '.test', function () {
 ...
  alert('test');
 });

Why?

为什么?

Answer:Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next ... link: https://api.jquery.com/on/

答:事件处理器只绑定到当前选中的元素;当您的代码调用.on() 时,它们必须存在于页面上。为确保元素存在且可以被选择,请在文档就绪处理程序中为页面上 HTML 标记中的元素执行事件绑定。如果将新 HTML 注入页面,则在将新 HTML 放入页面后选择元素并附加事件处理程序。或者,使用委托事件附加事件处理程序,如下所述...链接:https: //api.jquery.com/on/

回答by Jay Patel

Best way to apply event on dynamically generated content by using delegation.

使用委托在动态生成的内容上应用事件的最佳方法。

$(document).on("eventname","selector",function(){
    // code goes here
});

so your code is like this now

所以你的代码现在是这样的

$(document).on("click",".test",function(){
    // code goes here
});

回答by Nikolaus Pluta

$(.surrounding_div_class).on( 'click', '.test', function () {
alert( 'WORKS!' );
});

Will only work if the DIV with the class .surrounding_div_class is the immediate parent to the object .test

仅当具有 .surrounding_div_class 类的 DIV 是对象 .test 的直接父级时才有效

If there is another object in the div that will be filled it wont work.

如果 div 中有另一个对象将被填充,它将无法工作。