我有以下 jQuery 变量:
var confirmbox=$('<div></div>')
.data({'defaultText': 'This action cannot be reversed. Are you sure you wish to do this?',
'defaultButtons': { Yes : function() { $(this).dialog('close');},
No : function() { $(this).dialog('close');}
}
});
我想将 confirmbox.html()
设置为 confirmbox.data('defaultText')
。
confirmbox.html(confirmbox.data('defaultText'));//this works
confirmbox.html($(this).data('defaultText'));//this fails. Why?
同样的失败语法现在可以在这里使用:
confirmbox.dialog({
autoOpen: false,
modal: true,
buttons: $(this).data('defaultButtons'),
close: function(){
$(this).html($(this).data('defaultText')); //working here. Why?
$(this).dialog('option','buttons',$(this).data('defaultButtons'));
}
});
我认为我不明白 $(this)
在特定上下文中指的是什么。我怎么知道?
最佳答案
this
是对当前上下文对象的引用。在失败的示例中,this
可能指的是 window
对象(或者下一个直接封闭上下文,如果不是 window)。例如,如果 window
有自己附加的 defaultText
数据,则您可以将该传递到 .html()
.
但是由于 .html()
被设计为也将函数作为参数,因此在该函数中,this
将引用 confirmbox
上下文。尝试这样:
confirmbox.html( function(){
// this now refers to confirmbox
return $(this).data('defaultText');
});
关于jQuery element.data() 语法。我怎么知道 `$(this)` 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4694594/