2014-05-06 72 views
-1

我有下面的HTML代碼爲什麼jquery「this」沒有按預期工作?

<button id="b"> 
    Test 
</button> 

和JavaScript代碼

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

,但是當我點擊按鈕,名稱變量未控制檯

+2

預期值是多少? –

+0

你可以直接使用'this.name'它會工作! –

+0

這裏name只是一個不是按鈕名稱的局部變量。要爲按鈕指定名稱,您可以使用'this.name =「test button」' –

回答

3

您需要使用上進行打印:

console.log(name); 

因爲name是一個變種能在這裏。

Fiddle Demo

如果你想獲得按鈕的 id值,那麼

使用:

console.log(this.id); 
2

在你的函數,變量name僅僅是一個局部變量。它不是任何對象的屬性,所以當你做$(this).name它不是該jQuery對象的屬性。

如果你想只記錄本地變量到控制檯,你只需使用:

console.log(name); 

如果你想將其指定爲您的對象的屬性,那麼你就不會做本地變化的,但做到這一點,而不是:如果你想真正改變按鈕上的文字

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

,那麼你可以這樣做:

$("#b").click(function(){ 
    this.innerHTML = "test button"; 
}); 
1

如果您有:

<button id="b" name="test"> 
    Test 
</button> 

則:

$("#b").click(function(){ 

    console.log($(this).attr("name")); 
}); 

,如果你想獲得變量的值,那麼你就需要使用this

然後簡單地做到這一點:

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

Fiddle Example

0

$(這)是指對象,你可以看到有該對象中 嘗試沒有名稱屬性調試

console.log(name); 
0

這是因爲你在不同的範圍。 this引用按鈕,而不是剛創建的var。請參見下面的例子:

// First we provide a button 
<button id="lala">Click</button> 

一些JavaScript將遵循:

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

小提琴:http://jsfiddle.net/3WE6W/

如果您想了解更多有關JavaScript和的Populair Revealing module pattern(如myObject2)閱讀這篇文章:http://addyosmani.com/resources/essentialjsdesignpatterns/book/

相關問題