Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

javascript - jQuery如何将onclick事件绑定到动态添加的HTML元素(jQuery how to bind onclick event to dynamically added HTML element [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

I want to bind an onclick event to an element I insert dynamically with jQuery

(我想将onclick事件绑定到我使用jQuery动态插入的元素)

But It never runs the binded function.

(但是它从不运行绑定函数。)

I'd be happy if you can point out why this example is not working and how I can get it to run properly:

(如果您能指出此示例为何不起作用以及如何使其正常运行,我将不胜感激:)

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da"> <head> <title>test of click binding</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> jQuery(function(){ close_link = $('<a class="" href="#">Click here to see an alert</a>'); close_link.bind("click", function(){ alert('hello from binded function call'); //do stuff here... }); $('.add_to_this').append(close_link); }); </script> </head> <body> <h1 >Test of click binding</h1> <p>problem: to bind a click event to an element I append via JQuery.</p> <div class="add_to_this"> <p>The link is created, then added here below:</p> </div> <div class="add_to_this"> <p>Another is added here below:</p> </div> </body> </html> 

EDIT: I edited the example to contain two elements the method is inserted to.

(编辑:我编辑了该示例,以包含方法插入到其中的两个元素。)

In that case, the alert() call is never executed.

(在这种情况下,永远不会执行alert()调用。)

(thanks to @Daff for pointing that out in a comment)

((感谢@Daff在评论中指出这一点))

  ask by Jesper R?nn-Jensen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All of these methods are deprecated.

(所有这些方法均已弃用。)

You should use the on method to solve your problem.

(您应该使用on方法来解决您的问题。)

If you want to target a dynamically added element you'll have to use

(如果要定位动态添加的元素,则必须使用)

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

this replace the deprecated .live() method.

(替换不推荐使用的.live()方法。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...