【问题标题】:Can't change the button's value with jQuery无法使用 jQuery 更改按钮的值
【发布时间】:2018-01-16 09:09:26
【问题描述】:

我正在尝试使用 jQuery 更改按钮的值。

这是我在 html 中的内容:

<button id="choice1">John</button>

这就是我试图改变的价值:

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).val("Mike");  
    });
});

我什至试过.attr / .prop / .html / .text 而不是.val 但它们都不起作用。

好的,如果我尝试将其更改为这样的数组:

var a = new Array(4000)

a[2][1] = "North"
a[2][2] = "South"
a[2][3] = "East"
a[2][4] = "West"

以及功能:

function state1gmg(){
$(document).ready(function(){
    $("div#gamestatesdiv").text(state1);
});

$(document).ready(function(){
    $("div#questionsdiv").text(q[1]);
});

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).html(a[2][1]);  
    });
});

}

有什么帮助吗?提前致谢!!

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

您可以更改值,但是您想要对按钮执行的操作(与输入不同)是更改 HTML(或文本):

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).html("Mike");  
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="choice1">John</button>

【讨论】:

  • 为什么是html而不是文本?
  • @qiAlex - 完全没有理由。正如我在回答中所说,两者都可以正常工作。我只需要选择一个并且两者都可以工作,因为 &lt;button&gt; 可以同时包含两者。
  • 嗯,是的,效果很好,但前提是我将其更改为“Mike”之类的文本。例如,如果我想将其更改为变量怎么办?
  • @DuarteArribas 然后你将传递.html()(或.text())一个变量而不是一个字符串。例如:$(this).html(myVar)
  • @j08691 天哪,我想通了。都是我的错。我不得不输入for(i = 1; i &lt;= 4; i++){ a[i] = new Array(4) } 来放置第二个数组,但我没有这样做。谢谢大家的帮助!!!!!!
【解决方案2】:

更改&lt;button&gt; 值需要更改.text.html

在这个 sn-p 中,.text 按预期工作:

$(document).ready(function(){
    $("#choice1").click(function(){
        $(this).text("Mike");  
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<button id="choice1">John</button>

【讨论】:

    【解决方案3】:

    您应该使用text()html() 而不是val()

    $(document).ready(function(){
        $("#choice1").click(function(){
            $(this).text("Mike");  
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="choice1">John</button>

    【讨论】:

      【解决方案4】:

      $(document).ready(function(){
          $("#choice1").click(function(){
              $(this).val("Mike");  
              console.log ($(this).val()); // Mike. This changes value, but I suppose that you want to change inner text
              $(this).text("Mike");  // now the visible text will be Mike
          });
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
      <button id="choice1">John</button>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-01
        • 2014-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多