2013-01-10 43 views
0

在下面的代码中,我在使用jQuery显示在div中的数组中有一些注释。每个评论都有一个选项按钮,它可以正常工作,直到我发布新评论。我尝试过为每个元素使用唯一的ID,但它也不起作用。动态生成的html元素停止工作

当页面加载时,选项按钮有效;但是当我提交新评论时,没有任何按钮可以工作。我究竟做错了什么?

这里是我的脚本:

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/

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

回答

3

您需要使用委派:

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

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

注意:您可能需要使用比document以外的静态元素。 (有些父母div总是在网页上或其他东西)

+1

一个好的静态父元素将是'#comment_container' –

+0

就是这样!非常感谢,我不了解代表团。 – user1899500

2

仅仅因为您动态添加元素,所以点击不会对这些元素起作用,因此您必须在页面上找到最接近的现有父级,这里是您的案例这是comment_container并使用.on()处理程序:http://jsfiddle.net/fahKb/4/

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

非常感谢您的回答,这确实是我需要的,但凯文先回答,我想我应该选择他的答案,因为两者基本相同。但是你的回答帮助我更好地理解了我的问题。再次感谢。 :) – user1899500

+0

太棒了!快乐,我们帮助你。祝你好运 :) – Jai

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

这第一个反应是正确的,这样做的原因是,当元素被加载到DOM您分配事件侦听器。基本上说,如果这是'点击',然后做一些事情。问题是,添加新元素时,您还没有添加事件侦听器。通过做类似上面的代码,基本上你在做的是搜索文档中的所有内容,然后有“.options”类,最后如果它被点击,然后执行和执行一些代码。

这样说的使用文件不是最优化的方法,但它有时是必要的。一个更好的解决方案是,如果你想把所有的注释都换成“div”或其他元素,然后通过它来代替文档。这将不会搜索整个文档中的'.options',它只会搜索你的包装消除许多不必要的工作。

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