将onclick功能分配给动态创建的按钮(Assigning onclick function to dynamically created button)
遵循最佳实践,使用回调函数并处理最初的父加载div,我这样做:
$("#buttons_div"). html('<input type="button" value="Click me" id="button1" />', function() { $("#buttons_div"). on("click", "#button1", function() { alert("alert") }); });<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="buttons_div"> </div>为什么这不起作用?
Following the best practises, with callback functions and dealing with the initially parent loaded div, I did this:
$("#buttons_div"). html('<input type="button" value="Click me" id="button1" />', function() { $("#buttons_div"). on("click", "#button1", function() { alert("alert") }); });<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="buttons_div"> </div>Why this doesn't work?
最满意答案
这不行。 这两个陈述应该是分开的。 您不能将事件处理程序作为参数传递给.html()函数。 你需要这样做:
$(function() { $("#buttons_div").html('<input type="button" value="Click me" id="button1" />'); $("#buttons_div").on("click", "#button1", function() { alert("alert") }); });<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="buttons_div"> </div>This won't work. The two statements should be separate. You cannot pass the event handler as an argument to the .html() function. You need to do this way:
$(function() { $("#buttons_div").html('<input type="button" value="Click me" id="button1" />'); $("#buttons_div").on("click", "#button1", function() { alert("alert") }); });<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="buttons_div"> </div>
更多推荐
id,#buttons_div,div,电脑培训,计算机培训,IT培训"/> <meta name="descripti
发布评论