在 jQuery 的 setInterval 中使用 $(this) [英] Using $(this) inside a setInterval in jQuery
本文介绍了在 jQuery 的 setInterval 中使用 $(this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 jQuery 插件中使用此代码:
I am using this code inside a jQuery plugin:
setInterval(function() {
localStorage.setItem("flag", "set");
var data = $(this).serializeArray();
console.log($(this));
$.each(data, function(i, obj) {
localStorage.setItem(obj.name, obj.value);
});
console.log('saved');
console.log(localStorage);
}, 5000);
if (localStorage.getItem("flag") == "set") {
alert("This form has saved data!");
var data = $(this).serializeArray();
console.log($(this));
$.each(data, function(i, obj) {
$("[name='" + obj.name +"']").val(localStorage.getItem(obj.name));
});
}
现在奇怪的是,第一个 $(this)
包含表单(运行插件),但第二个 $(this)
包含 DOMWindow代码>.为什么两个
$(this)
包含不同的东西?是因为第一个在 setInterval
中吗?
Now strangely, the first $(this)
contains the form (which the plugin is ran on), but the second $(this)
contains DOMWindow
. How come the two $(this)
contain different things? Is it because the first is inside a setInterval
?
推荐答案
你可以使用简单的闭包,也可以使用 $.proxy
: http://api.jquery.com/jQuery.proxy/
You can either use a simple closure, or use $.proxy
: http://api.jquery.com/jQuery.proxy/
var repeat = function() {
localStorage.setItem("flag", "set");
var data = $(this).serializeArray();
.......
}
setInterval($.proxy(repeat, $("#form")), 500);
类似的东西...
这篇关于在 jQuery 的 setInterval 中使用 $(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文