在其click事件处理程序中访问按钮的属性

时间:2015-12-23 02:02:23

标签: javascript jquery

按钮:

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

按钮的点击处理程序:

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

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

    e.preventDefault();
});

我可以使用上面的代码在点击处理程序中获取按钮的id。如何获取按钮的值(即“按钮标签”)或点击处理程序中的其他属性?

(虽然我们在讨论这个问题时,为什么有时我们需要做jQuery:this(例如,上面),有时我们需要这样做:$(this)。 ..请问有什么区别的简单解释吗?

2 个答案:

答案 0 :(得分:3)

如果您想要检索文字,请访问textContent property上的DOM element

this.textContent // Button Label

或者使用jQuery .text() method

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

为什么有时我们需要使用jQuery:this(例如,上面)以及其他时候我们需要这样做:$(this)

在这种情况下,thisDOM element,而$(this)jQuery object

原生DOM元素具有属性,例如valueidtextContent

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

值得指出的是,无法直接在DOM元素上使用jQuery方法,这就是为什么要将this$()一起包装以将其转换为jQuery对象。

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

答案 1 :(得分: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