javascript 不适用于通过 jquery 新添加的innerhtml

发布于 2024-09-08 15:56:38 字数 656 浏览 1 评论 0原文

我有以下 HTML 结构,

<table>
<tr>
   <div id="getData">
   </div> 
</tr>
</table>

我使用 jquery 的 html() 方法将动态内容添加到 div id“getData”,如下所示:

  $('#valueResult').html(data);
    var data ="
<table><tr><td><input type="checkbox" name="test[1]" onclick="doSometing()" /> Test</tr></tr></table> 
    <table><tr><td><input type="checkbox" name="test[2]" onclick="doSometing()" /> Test</tr></tr></table> "  

但是函数 doSometing() 永远不会对任何动态添加的复选框执行。 为什么会这样?

谁能帮我吗?

谢谢。

I have following HTML structure

<table>
<tr>
   <div id="getData">
   </div> 
</tr>
</table>

I am using jquery's html() method to add dynamic contents to div id "getData" as:

  $('#valueResult').html(data);
    var data ="
<table><tr><td><input type="checkbox" name="test[1]" onclick="doSometing()" /> Test</tr></tr></table> 
    <table><tr><td><input type="checkbox" name="test[2]" onclick="doSometing()" /> Test</tr></tr></table> "  

But the function doSometing() is never executed for any of the dynamically added checkboxes.
why so ?

can anyone help me out ?

THX.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寂寞花火° 2024-09-15 15:56:38

针对此类问题的更简洁的 jQuery 解决方案是使用 .live() 甚至更好的 .delegate()

使用这种方法,您还应该为您的输入元素提供唯一的ID并调用:

$(document).ready(function(){
   $('#unique_input_id').live('click', function(){
      alert('clicked');
   });
});

参考: .live(), .delegate()

A cleaner jQuery solution for a problem like this is to use .live() or even better .delegate().

With this approach you should also give your input element an unique id and call:

$(document).ready(function(){
   $('#unique_input_id').live('click', function(){
      alert('clicked');
   });
});

Reference: .live(), .delegate()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文