jQuery element.data()语法.我怎么知道`$(this)`是什么? [英] jQuery element.data() syntax. How do I know what `$(this)` is?

查看:571
本文介绍了jQuery element.data()语法.我怎么知道`$(this)`是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下jQuery变量:

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');}
               }
        });

我要将confirmbox.html()设置为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'));
            }
        });

我认为我不理解$(this)在特定上下文中指的是什么.我怎么知道?

I think that I don't understand what $(this) is referring to in particular contexts. How do I tell?

推荐答案

this是对当前上下文对象的引用.在失败的示例中,this可能是引用window对象(或下一个直接封闭的上下文,如果不是window的话).例如,如果window具有自己的附加defaultText数据,则将那个传递给.html().

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().

但是,由于.html()被设计为还接受一个函数作为参数,因此在该函数内,this将引用confirmbox上下文.像这样尝试:

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');
});

这篇关于jQuery element.data()语法.我怎么知道`$(this)`是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆