我的jQuery插件有问题。我不能发布整个脚本,因为它太大了,这是一个小的和修改过的摘录。基本上它以这种方式工作:
但是上面有一些错误。当连续3次执行呼叫时,备份的孩子可能空了!
非常感谢任何帮助。以下是控制流程的简化版本:
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之前没有克隆备份!
答案 0 :(得分:1)
第二个if - $。类型行的括号是什么? =)
好的,明白了。不知道如何阅读所有这些“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>