将onclick功能分配给动态创建的按钮(Assigning onclick function to dynamically created button)

系统教程 行业动态 更新时间:2024-06-14 17:01:31
将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

本文发布于:2023-04-20 16:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/d70f397bb8fde81d332601fec0b3fb66.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按钮   功能   动态   onclick   Assigning

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!