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



在下面的代码中,我在一个数组中有一些注释,这些注释使用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");
});
});

这里有一把小提琴来看看它是如何工作的。http://jsfiddle.net/fahKb/3/

谢谢你花时间阅读这个问题。

您需要使用委派:

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

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

注意:您可能希望使用document以外的静态元素。(一些总是在页面上的父div或其他什么。(

因为您是动态添加元素的,所以单击无法处理这些元素,所以您必须在页面上找到最接近的现有父级,在您的情况下,这里是这个comment_container,并使用.on()处理程序:http://jsfiddle.net/fahKb/4/

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

第一个响应是正确的,原因是当元素加载到DOM中时,您分配了事件侦听器。本质上是说嘿,如果点击了,那就做点什么。问题是,在添加新元素时,您还没有添加事件侦听器。通过执行类似于上面代码的操作,您所做的基本上是搜索文档中的所有内容,然后搜索类为".options"的内容,最后如果单击了它,则执行一些代码。

也就是说,使用文档不是最理想的方法,但有时也是必要的。一个更好的解决方案是,如果您将所有注释包装在一个"div"或其他元素中,然后传递它来代替文档。这将不会在整个文档中搜索".options",只会搜索包装,从而消除大量不必要的工作。

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

最新更新