![](/img/trans.png)
[英]Trying to iterate through an object and append resutls to DOM element to create a grid
[英]trying to append content to DOM element
我试图通过单击按钮将div添加到一行内容。 我的代码适用于第一行,但不适用于其他任何行。 请帮忙。 这是按钮的功能:
$(".addMMbtn").each(function() {
$(this).bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
});
您可以在这里看到问题的小提琴: http : //jsfiddle.net/z7uuJ/
您无需遍历元素即可绑定处理程序:
$(".addMMbtn").live('click', function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
});
$(".addMMbtn")
将仅找到页面上存在的元素,并且您的代码将仅在其上附加click
事件处理程序。 由于您是动态添加元素的,因此您应该使用delegate
或on
(如果您使用的是jQuery 1.7+)的click
事件也可以对其进行处理。 尝试这个
使用delegate
$('#default').delegate('.addMMbtn', 'click', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
on
使用
$('#default').on('click', '.addMMbtn', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
无需直接在按钮上分配click事件,您需要使用on()
:
$(document).on("click", ".addMMbtn",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
在这种情况下,事件处理程序将订阅所有新添加的元素。
代码: http : //jsfiddle.net/z7uuJ/5/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.