我有一个 bootstrap 按钮,显示"显示用户信息"作为按钮标签。当用户点击按钮时,我想将标签更改为"仅显示用户"用户点击"仅显示用户"它必须将按钮标签更改为"显示用户信息"。
<button class="btn btn-primary" type="button" onclick="myFunction()" id="myButton1">Show User Information</button>
js code:
function myFunction() {
var elem = document.getElementById("myButton1");
if (elem=="Show User Information") elem.value = "Display Only Users";
else elem.value = "Show User Information";
}
单击时,上面的js代码不会更改按钮标签。有什么输入吗?
答案 0 :(得分:1)
为按钮添加值属性
value="Show User Information"
并使用和比较
在js中检索ele.value=="Show User Information"
答案 1 :(得分:1)
您需要检查按钮的文本,而不是元素本身
function myFunction() {
var elem = document.getElementById("myButton1"),
text = elem.textContent || elem.innerText;
if (text === "Show User Information")
elem.innerHTML = "Display Only Users";
else
elem.innerHTML = "Show User Information";
}
<button class="btn btn-primary" type="button" onclick="myFunction()" id="myButton1">Show User Information</button>