问题
I have the following jQuery variable:
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');}
}
});
I want to set confirmbox.html() to confirmbox.data('defaultText').
confirmbox.html(confirmbox.data('defaultText'));//this works
confirmbox.html($(this).data('defaultText'));//this fails. Why?
And the same failing syntax now works here:
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'));
}
});
I think that I don't understand what $(this) is referring to in particular contexts. How do I tell?
回答1:
this is a reference to the current context object. In your example that fails, this is probably referring to the window object (or whatever the next immediate enclosing context is, if not window). If window had its own attached defaultText data, for example, you'd be passing that into .html().
But since .html() is designed to also take a function as an argument, within that function, this will refer to the confirmbox context. Try it like this:
confirmbox.html( function(){
// this now refers to confirmbox
return $(this).data('defaultText');
});
回答2:
Like you said, it's all about the context.
When the dialog.close() function is executed, the this object points to the dialog instance, as a result $(this) refers to the jQuery dialog object. If you're executing
confirmbox.html($(this).data('defaultText'));//this fails. Why?
in a global context, this doesnt have that meaning. it refers to the document.window object, not your dialog instance.
回答3:
In confirmbox.dialog, this refers to the the confirmbox object. That's why $(this) worked.
In the line confirmbox.html($(this).data('defaultText'));, this has no context, and is just set to window.
I'm not very good at explaining things, but I hope this helped.
来源:https://stackoverflow.com/questions/4694594/jquery-element-data-syntax-how-do-i-know-what-this-is