我有以下脚本将 jquery 对象的颜色更改为蓝色:
$(".objects_list").live('click', function(event)
{
$(this).css("color", "blue");
});
我如何记住 $(this) 是什么,以便我可以再次更改颜色,但是来自不同的函数或来自不同对象的事件?
最佳答案
除了全局变量,您还可以使用 jQuery 的 data() 方法将信息与文档本身相关联:
$(".objects_list").live('click', function(event) {
$(this).css("color", "blue");
$(document).data("yourObjectKey", $(this));
});
然后您可以在以后轻松获取该信息:
$("otherSelector").click(function() {
var yourObject = $(document).data("yourObjectKey");
if (yourObject != null) {
yourObject.css("color", "red");
}
});
编辑: 如果元素在两个事件之间被销毁并重新创建,则该方法将不起作用。在这种情况下,您可以存储元素的
id
而不是对元素本身的引用:$(".objects_list").live('click', function(event) {
$(this).css("color", "blue");
$(document).data("yourObjectKey", this.id);
});
然后:
$("otherSelector").click(function() {
var yourObjectId = $(document).data("yourObjectKey");
if (yourObjectId != null) {
$("#" + yourObjectId).css("color", "red");
}
});
关于javascript - 记住 $(this) 是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4864614/