无法从$().data()中达到$(this)

dub*_*elj 3 javascript jquery

我正在尝试将我的元素的类设置在同一元素的数据对象中,但它仍然返回undefined.

$(this).data({
            orgSize:{ // Write all the sizes as data. For future reference.
                width: $(this).width(), //returns the width just fine!
                height: $(this).height() //returns the height just fine!
            },
            orgClass: function(){
                cl = $(this).attr('class');
                if(cl){
                    return ' ' + cl;
                }else{
                    return ' somethingelse';
                }
            } //returns undefined
        });

        console.log($(this).attr('class')) //returns the class
Run Code Online (Sandbox Code Playgroud)

编辑:问题在orgClass中.

Phr*_*ogz 6

var me = $(this);
me.data({
  orgSize  : { width:me.width(), height:me.height() },
  orgClass : function(){
    cl = me.attr('class');
    return cl ? (' '+cl) : ' somethingelse';
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 要添加到Phrogz答案,问题中的原始代码不起作用的原因是"this"基于函数调用的上下文而变化(很难说没有看到它是如何被调用的).确定'this'的值是JavaScript中常见的误解,我强烈建议@dubbelj阅读它.这个答案有效的原因是它将'this'的值捕获到所谓的'闭包'中,基本上在声明时锁定了值. (3认同)
  • 除了这个工作的事实,它还提供了性能提升.在同一个闭包中多次出现`$(this)`并不聪明,每次执行时都会反复运行`jQuery.init()`. (2认同)