为什么Jquery“this”没有按预期工作?

为什么Jquery“this”没有按预期工作?,jquery,this,Jquery,This,我有下面的html代码 <button id="b"> Test </button> ,但当我单击按钮时,控制台上没有打印名称变量您需要使用: console.log(name); 因为name在这里是一个变量 如果要获取按钮的id值,请使用: console.log(this.id); 在函数中,变量名只是一个局部变量。它不是任何对象的属性,因此当您执行$this.name时,它不是该jQuery对象的属性 如果只想将局部变量记录到控制台,只需使用: co

我有下面的html代码

<button id="b">
    Test
</button>
,但当我单击按钮时,控制台上没有打印名称变量

您需要使用:

console.log(name);
因为name在这里是一个变量

如果要获取按钮的id值,请使用:

console.log(this.id);

在函数中,变量名只是一个局部变量。它不是任何对象的属性,因此当您执行$this.name时,它不是该jQuery对象的属性

如果只想将局部变量记录到控制台,只需使用:

console.log(name);
如果要将其指定为对象的属性,则不会生成局部变量,而是执行以下操作:

$("#b").click(function(){
    this.name = "test button";
    console.log(this.name);
});
如果要实际更改按钮的文本,则可以执行以下操作:

$("#b").click(function(){
    this.innerHTML = "test button";
});
如果您有:

<button id="b" name="test">
    Test
</button>
如果您想要获取变量值,那么您不需要使用这个

然后简单地这样做:

$("#b").click(function(){
    var name = "test button";
    console.log(name);
});

$this引用对象,正如您所看到的,该对象中没有name属性 试着调试

console.log(name);

这是因为您在不同的范围内。这指的是按钮,而不是刚刚创建的变量。请参见以下示例:

// First we provide a button
<button id="lala">Click</button>
小提琴:


如果你想了解更多关于javascript和myObject2这样的大众展示模块模式的信息,请阅读这篇文章:

期望值是多少?你可以直接使用这个名称。它会起作用的!!!此处名称只是一个局部变量,不是按钮名称。若要为按钮指定名称,可以使用此名称。名称=测试按钮当您不指定按钮名称时,打印按钮名称有何用途?name是click函数的本地名称,而不是附加到$this,因此只需console.logname即可打印它。
console.log(name);
// First we provide a button
<button id="lala">Click</button>
function myObject() {
    this.hello = 'hello';
};

var myObject2 = (function () {
    var hello = 'hello';

    function getHello() {
        return hello;
    };

    return {
        getHello: getHello
    };
})();

// In your case
$('#lala').on('click', function () {
    this.hello = 'hello';

    console.log("I'm a property of the current 'this' : " + this.hello);
    console.log("I'm sent by the button, so in this case I'm the button : ");
    console.log(this);

    // Now lets see what happens if we log the 2 objects
    console.log(myObject.hello);

    var instanceOfObject = new myObject();

    console.log("Now I show you the 'hello'! : " + instanceOfObject.hello);

    // This will not work because it's the revealing module pattern(you can work a kind of with getters and setters). Directly calling 'hello' will not work(it's kind of private).
    console.log(myObject2.hello);

    console.log("Greetings from myObject2 : " + myObject2.getHello());
});