2016-09-27 121 views
0

无法获取jquery中的按钮值。如何获取jquery中的按钮值

<head> 
    <script   
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"> 
</script> 
</head> 

<body> 
    <p> This is para </p> 
    <button> Hide </button> 
    <script> 
      function handle(){ 
        value = $("button").attr("value"); 
        alert(value); 
      } 

      $(function(){ 
        $("button").click(handle); 
      }); 
    </script> 

什么是上面的代码中的错误。我需要处理由按钮触发的事件,而不是“this”。我已经看到如何使用“this”来解决它。因此,如果没有“this”,如何处理事件

+2

'button'没有'value'属性... –

回答

0

使用jQuery .text()方法与button元素来获取其中包含的文本值。 (例如,开放式<button>和关闭</button>标签之间的文本。)

什么你试图不工作,因为button元素没有value属性检索。

获取文本示例:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
<p> This is para </p> 

<button> Hide </button> 

<script> 
    function handle() { 
     var buttonText = $("button").text(); 

     // Whatever you need to do with the text. 
     alert(buttonText); 
    } 

    $(function(){ 
     $("button").click(handle); 
    }); 
</script> 

Working code pen

相反地,也可以通过使所希望的值将其用同样的方法设置button的文本值。

设置文本范例:

... 
    $("button").text("My New Text"); 
... 

文档:jQuery .text() Method

1

如果你希望得到您的按钮内部的文本只需使用:

value = $("button").text(),而不是value = $("button").attr("value")

您的按钮没有可用于获取数据的value属性。

所以,你应该用.text()方法,而不是.attr()

<body> 

    <p> This is para </p> 
    <button> Hide </button> 

<script src="https://code.jquery.com/jquery-3.1.0.js"></script> 

<script> 
    function handle(){ 
    value = $("button").text(); 
    alert(value); 
    } 

    $(function(){ 
    $("button").click(handle); 
    }); 
</script> 

</body> 

Working example in JSBin

0

按钮元素都有关联,所以你一定要试试标签中抓取文本<button></button>

可以使用没有价值属性jquery的text()方法抓取文本为

<html> 
<head><title>demo</title> 
<script src="https://code.jquery.com/jquery-3.1.0.js"></script> 
<script type='text/javascript'> 
     $(document).ready(function(){ 
     var x= $('#btn').text(); 
     console.log(x); 
}); 
</script> 
</head> 
<body> 
<button id='btn'>Click Me</button> 
</body> 
</html> 
相关问题