【发布时间】:2015-05-10 18:31:36
【问题描述】:
我将尝试解释我的问题: 我有一个网站,用户可以在其中动态添加元素。它们都属于“toBuy”类。每当将新元素添加到此类时,我都需要仅将点击处理程序附加到该元素而不附加到所有其他元素。为了保持我的代码干净,我想要一个可以完成这项工作的函数。这是我尝试过的:
这就是添加东西的方式:
$("#addItemButton").click(function(){
var item= $('#item').val();
$('#item').val("");
var quantity= $('#quantity').val();
$('#quantity').val("");
var comment=$('#addComment').val();
$('#addComment').val("");
//construct new html
var newitem="<div class='toBuyItem'><div class='item'>";
newitem+=item;
newitem+="</div><div class='quantity'>";
newitem+=quantity;
newitem+="</div><div class='comment'><img src='img/comment";
if(comment==""){
newitem+="_none"
}
newitem+=".png' alt='Comment'></div><div class='itemComment'>"
newitem+=comment;
newitem+="</div></div>";
$("#toBuyItems" ).prepend( newitem );
toggle("#addItemClicked");
initializeEventListeners();
});
然后这是 initializeEventListeners 函数(我也在页面加载时运行它,以便现有元素已经具有事件处理程序:
function initializeEventListeners(){
$(".toBuyItem").click(function(){
console.log($(this).html());
console.log($(this).has('.itemComment').length);
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
}
function toggle(item){
$( item ).slideToggle(500);
}
现在显然发生的情况是,当添加一个新元素时,现有元素会获得一个新的事件处理程序来点击(所以他们有两次)。这意味着它们只需单击一下即可打开和关闭。可能这该死的简单,但我无法理解它....
编辑: 所以这行得通:
$(document).on('click', '.toBuyItem', function(){
if($(this).has('.itemComment').length != 0){
console.log("toggling");
$(this).addClass("toggling");
toggle(".toggling .itemComment");
$(this).removeClass("toggling");
}
});
【问题讨论】:
标签: javascript jquery html