jQuery 具有动态创建的元素和事件处理程序的数据
jQuery data with dynamically created elements and event handlers
我想知道为什么更新动态创建的元素的数据会影响之前创建的其他元素的数据。
这里是例子http://jsfiddle.net/bmq3sk9c/
var createComment = function(data) {
var post = $("<div/>").addClass("com").html("lorem "+Math.floor((Math.random()*10)+1)).data("extra", data);
var btn = $("<a/>", {href:"",class:"sbm"}).text("submit");
post.append(btn);
post.on("submit", submitComment);
post.appendTo("body");
};
var submitComment = function(e){
//ajax here
$(this).data("extra").time = new Date().getTime();//why this affects data of previously created comments
$(this).find(".sbm").remove();
test();
};
var test = function(){
$("body").find(".com").each(function(){
console.log($(this).data("extra"));
});
}
var d = {
param: "test",
a: "another"
};
$(".crea").on("click", function(e){
e.preventDefault();
createComment(d);
});
$("body").on("click", ".sbm", function(e){
e.preventDefault();
$(this).closest(".com").trigger("submit");
});
我猜是什么问题...但我想知道如何解决,非常感谢!
由于使用对象,发生了数据共享。您应该将对象的深层副本传递给 .data() 以防止它:
var createComment = function(data) {
var post = $("<div/>").addClass("com").html("lorem "+Math.floor((Math.random()*10)+1))
post.data("extra", $.extend({}, data));
/* ... */
};
我想知道为什么更新动态创建的元素的数据会影响之前创建的其他元素的数据。
这里是例子http://jsfiddle.net/bmq3sk9c/
var createComment = function(data) {
var post = $("<div/>").addClass("com").html("lorem "+Math.floor((Math.random()*10)+1)).data("extra", data);
var btn = $("<a/>", {href:"",class:"sbm"}).text("submit");
post.append(btn);
post.on("submit", submitComment);
post.appendTo("body");
};
var submitComment = function(e){
//ajax here
$(this).data("extra").time = new Date().getTime();//why this affects data of previously created comments
$(this).find(".sbm").remove();
test();
};
var test = function(){
$("body").find(".com").each(function(){
console.log($(this).data("extra"));
});
}
var d = {
param: "test",
a: "another"
};
$(".crea").on("click", function(e){
e.preventDefault();
createComment(d);
});
$("body").on("click", ".sbm", function(e){
e.preventDefault();
$(this).closest(".com").trigger("submit");
});
我猜是什么问题...但我想知道如何解决,非常感谢!
由于使用对象,发生了数据共享。您应该将对象的深层副本传递给 .data() 以防止它:
var createComment = function(data) {
var post = $("<div/>").addClass("com").html("lorem "+Math.floor((Math.random()*10)+1))
post.data("extra", $.extend({}, data));
/* ... */
};