javascript - 单击多个按钮后,如何更改使用 <button> 标签创建的按钮的文本?

标签 javascript jquery html

我正在使用由按钮标签创建的多个按钮,我想仅在单击该按钮时分别更改每个按钮的文本。
我正在尝试使用以下代码,但它根本不起作用。 我怎样才能通过使用按钮标签来做到这一点...... 谢谢...

HTML代码是

user1
<button class="toggle" href="/" onclick ="myFunction(this)">connect</button>
user2
<button class="toggle" href="/" onclick ="myFunction(this)">connect</button>
user3
<button class="toggle" href="/" onclick ="myFunction(this)">connect</button>

而js代码是

<script>
function myFunction(obj) {
if (obj.value == "Connected")
    obj.value = "Connect";
else
    obj.value = "Connected";
}
</script>

最佳答案

您需要更改 innerText 而不是 value 并且区分大小写

按钮有value属性但没有href属性

注意如果按钮在表单中,你需要使用type="button" 或者添加preventDefault 来不提交表单

内联纯 JS:

function myFunction(obj) {
  obj.innerText = obj.innerText == "Connect" ? "Connected" : "Connect";
}
user1
<button class="toggle"  onclick="myFunction(this)">Connect</button> user2
<button class="toggle"  onclick="myFunction(this)">Connect</button> user3
<button class="toggle"  onclick="myFunction(this)">Connect</button>

jQuery - 带链接

$(function() {
  $(".toggle").on("click", function() {
    var text = $(this).text(), link = $(this).data("url");
    $(this).text(text == "Connect" ? "Connected" : "Connect");
    $("#somediv").load(url);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
user1
<button data-url="user1.html" class="toggle">Connect</button> user2
<button data-url="user2.html" class="toggle">Connect</button> user3
<button data-url="user3.html" class="toggle">Connect</button>

关于javascript - 单击多个按钮后,如何更改使用 <button> 标签创建的按钮的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44847687/

相关文章:

javascript - javascript 按钮不显示

javascript - JqG​​rid - 使用 formatDisplayField 选项

javascript - 如何强制 TinyMCE 在 P 标签内创建 SPAN 标签?

html - 复杂的 HTML 表单

html - HTML5足够稳定吗?

javascript - 无法连续两次启动相同的动画

javascript - 如何使用 javascript 获取完整日期?

javascript - 如何更改浏览器选项卡在 JSFiddle 中显示的文本

javascript - 点击播放视频的功能在平板电脑上不工作

javascript - 检测 JQuery 动画的结束