【问题标题】:How to get value for a input button using jquery?如何使用 jquery 获取输入按钮的值?
【发布时间】:2012-03-15 13:55:05
【问题描述】:

我需要使用 jquery 检索可点击按钮的值。我在<div> 下有 3 个按钮:

<div class="button1">
        <input type="button" value="one" id="One" onclick= "location.href='index.html'"/> 
        <input type="button" value="two" id="Two" onclick="location.href='index.html'" />
        <input type="button" value="three" id="Three" onclick="location.href='index.html'" />
 </div> 

如果我点击按钮 1,我需要获取按钮 1 的值。我不知道,究竟如何获取 this 的值。

这是我的 js:

$(document).ready(function() {
    $('.button1').click(function() {
        var text = $(this).text();
        $("input").val(text);
        });
});

我知道我写的这个脚本是错误的,因为我得到的值是“一、二、三”。

【问题讨论】:

    标签: jquery get


    【解决方案1】:

    与任何其他输入一样,要获取按钮的值,请使用 .val():

    $('input:button').click(function() {
        alert($(this).val());
    });​
    

    http://jsfiddle.net/3QDM5/

    我不确定你到底想用你的脚本做什么!

    【讨论】:

      【解决方案2】:

      使用属性 http://api.jquery.com/attr/

      $(document).ready(function() { 
          $('#button1').click(function() { 
              var text = $(this).attr('value'); 
              $("#input").val(text); 
          }); 
      }); 
      

      【讨论】:

        【解决方案3】:

        示例:

        <input type="button" value="one" id="One" onclick= "click(this.value)'"/>
        

        其中 click(this.value) 是 javascript 上的函数

        function click(x)
        {
            //x is value from onclick button
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-10-20
          • 1970-01-01
          • 2015-09-09
          • 1970-01-01
          • 2021-08-25
          • 2021-10-28
          • 1970-01-01
          相关资源
          最近更新 更多