javascript - 动态生成的 html 元素停止工作

标签 javascript jquery

在下面的代码中,我在数组中有一些注释,这些注释使用 jQuery 显示在 div 中。每个评论都有一个选项按钮,在我发布新评论之前该按钮可以正常工作。我尝试为每个元素使用唯一的 ID,但它也不起作用。

页面加载时,选项按钮起作用;但是当我提交新评论时,所有按钮都不起作用。我究竟做错了什么?

这是我的脚本:

var i = 0;
var comments_display= "";
var comments = ['Hello World!', 'Hello! This is a comment.'];

//reads the entire array, creates the content, and sends it to the div
function show_comments(){
   for (i=0; i<comments.length; i++){
     comments_display += "<div class='single_comment_container'>";
     comments_display += "<div class='comment_comment'>" + comments[i] + "</div>";
     comments_display += "<div class='options'>Options</div></div>";
    }
    $("#comment_container").html(comments_display);
    comments_display = "";
 }

//appends a new comment to the array
function new_comment(){
   if ($("#comment_input").val() == null || $("#comment_input").val() == ""){
      alert("Your comment must be at least 1 character long.");
   }

   else{
      comments.push($('#comment_input').val());
       show_comments();
       $("#comment_input").val("");
   }
}

$(document).ready(function(){
   show_comments();

   $("#submit_comment").click(function(){
      new_comment();
   });

//display a message when an element of the class 'options' is clicked
$(".options").click(function(){
   alert("OPTIONS");
});

});

这里有一个 fiddle 来看看它是如何工作的。 http://jsfiddle.net/fahKb/3/

感谢您花时间阅读此问题。

最佳答案

您需要使用委托(delegate):

$(document).on( 'click', '.options', function() {
   alert("OPTIONS");
});

http://api.jquery.com/on/

注意:您可能想要使用 document 以外的静态元素。 (某些父 div 始终位于页面或其他内容上。)

关于javascript - 动态生成的 html 元素停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14265242/

相关文章:

javascript - 单击图标播放以开始声音,然后单击停止图标以停止声音

javascript - 动态为每个元素创建新的唯一 ID

javascript - jquery 点击模拟不起作用

javascript - 包装一个 jquery 函数并返回一个值

Jquery 单击事件在第一次单击时不执行

jquery - 在谷歌地图中创建自定义信息窗口

javascript - 为什么我需要 @babel/polyfill,使用 Babel?

javascript - Angular Directive(指令)属性未检测到的变化

javascript - 类型错误 : undefined' is not a function (evaluating 'myAudio.play()' )"

javascript - 其中每个变量等于 spans content add class