2015-12-23 33 views
1

內部的按鈕:訪問一個按鈕的屬性其Click事件處理程序

<button class='button pasteButton' id='pasteButton1'>Button Label</button> 

按鈕的Click處理程序:

$(document).on('click','.pasteButton',function(e){ 

    //alert("paste clicked"); 
    alert(this.id); 

    e.preventDefault(); 
}); 

我能夠獲得按鈕的id與上述點擊處理程序中碼。我怎樣才能得到按鈕的值(即「按鈕標籤」)或點擊處理程序內的其他一些屬性? (而且,雖然我們在這個問題上,爲什麼有時我們需要做:this(例如上面),在其他時候我們需要做:$(this) ...有沒有一個簡單的解釋的差異,請

回答

3

如果你要檢索的文本,無論是在DOM element訪問textContent property

this.textContent // Button Label 

或者使用jQuery的.text() method

$(this).text() // Button Label 

爲什麼是它與jQuery的,有時我們需要做的:this(例如,以上)和在其他時間,我們需要做的:$(this)

在這種情況下,thisDOM element,而$(this)jQuery object

原生DOM元素具有屬性,例如value,id,textContent

this.id // pasteButton1 
this.textContent // Button Label 

值得指出的是,你不能使用jQuery方法直接在DOM元素,這就是爲什麼你才能把它變成一個jQuery對象與$()包裝this

$(this).prop('id') // pasteButton1 
$(this).text() // Button Label 
+1

非常感謝你非常。真的很好地澄清事情。巨大的幫助。我希望DOM和jQuery之間的一些術語沒有那麼不同。 (例如,在HTML中,我認爲我們引用按鈕元素的標籤,因爲它的值)。並且在爲'.text()'方法文檔提供的鏈接中,單詞「按鈕」不會出現在頁面上,因此,對於像我這樣的半新手來說,理解連接。 –

+0

@ user1883050我很高興幫助。像大多數事情,我認爲這只是需要練習:) –

+0

'1'的解釋。 – shakhawat

1
<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $("#mButton").click(function(){ 
     alert("name:"+ $(this).attr("value")); 
    }); 
}); 
</script> 
</head> 
<body> 

<input id="mButton" type = "button" value="submit"/> 

</body> 
</html> 

DEMO

相關問題