Javascript jQuery clone()包含子元素并保存到data()作为备份的元素?
我的jQuery插件有问题。我不能发布整个脚本,因为它太大了,这是一个小的修改摘录。基本上它是这样工作的:Javascript jQuery clone()包含子元素并保存到data()作为备份的元素?,javascript,jquery,dom,jquery-plugins,Javascript,Jquery,Dom,Jquery Plugins,我的jQuery插件有问题。我不能发布整个脚本,因为它太大了,这是一个小的修改摘录。基本上它是这样工作的: ajax调用,如果结果集为空,则备份元素及其内容(如果尚未定义备份),并覆盖其内容 如果结果集包含数据,请查找其中的某些元素,并使用.html()显示数据 但是上面有一些错误。当调用连续执行3次时,备份的子项很遗憾是空的 非常感谢您的帮助。以下是控制流的简化版本: var backup = function() { this.data('backup', this.clone(true))
var backup = function() { this.data('backup', this.clone(true)); }
var onObjectProperty = function(obj) {
// This is where my script fail!!! 3 consecutive times of empty data,
// and children() contains no data!
if($.type(this.data('backup')) !== 'undefined')
console.log(this.data('backup').children());
};
if(!val.error && !val.count) // Not an error, but data is empty
{
// Keyword "this" is the current element in selection loop (on which
// the plugin was invoked)
if($.type(context.data('backup')) === 'undefined')
backup.call(this); // Backup if not already defined
opt.onEmpty.call(context); // Call the function to handle empty data
return true; // Skip the current iteration in the loop
}
// Here we have no errors and result set contains data
onObjectProperty.call(this, obj); // Pass the context and the data
编辑:发现错误,在将备份添加到DOM之前未克隆备份 第二行if-$.type的括号是什么?=) 好的,明白了。不确定如何读取所有这些“obj”、“context”和“val”,以及它们如何适应,但为了实现它的价值,我设法实现了来回数据的备份,请参见下文 好主意
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
var backup = function() { this.data("backup", this.clone(true)); }
function doit(x) { if ($.type(x.data("backup")) == "undefined") { backup.call(x); } }
function dumpit(x) {
if ($.type(x.data("backup")) != "undefined") {
console.log("backup", x.data("backup"));
console.log("children", x.data("backup").children());
}
}
function addit(x) {
if ($.type(x.data("backup")) != "undefined") {
var x = x.data("backup").clone();
x.attr("id",null);
$("body").append(x);
}
}
</script>
</head>
<body>
<div id="xxx" class="yyy">
<p class="zzz">helu</p>
<a href="#">there</a>
<input></input>
</div>
<button onclick="doit($('#xxx'));">do</button>
<button onclick="dumpit($('#xxx'));">see</button>
<button onclick="addit($('#xxx'));">add</button>
</body>
</html>
var backup=function(){this.data(“backup”,this.clone(true));}
函数doit(x){if($.type(x.data(“备份”))==“未定义”){backup.call(x);}
函数dumpit(x){
如果($.type(x.data(“备份”))!=“未定义”){
console.log(“备份”),x.data(“备份”);
console.log(“children”,x.data(“backup”).children();
}
}
函数加法器(x){
如果($.type(x.data(“备份”))!=“未定义”){
var x=x.data(“备份”).clone();
x、 属性(“id”,空);
$(“正文”)。附加(x);
}
}
helu
做
看见
添加
已修复,结果也没有更改。感谢您的努力,+1仅用于尝试。去测试并报告!你让我开心!错误不是克隆备份本身(以及在修改备份后不久)!啊,他们又是一双眼睛,耶!