我正在尝试使用onclick函数更改输入按钮的值,但是无论我做什么,我似乎都无法正常工作,而且我在这里找到的所有答案似乎都没有帮助
function button() {
var btn = document.getElementById("tz");
if (btn.value == "UTC") {
btn.value = "Local time";
} else {
btn.value = "UTC";
}
}
<input type="button" id="tz" onclick="button()" value="UTC">
答案 0 :(得分:0)
这是.value与.innerHTML的一种情况...您正在更改.value(它可以工作),但您也没有更新button.innerHTML(标签...不是值)...
<script>
function changeValue(button) {
console.log('The original value of the button is: ', button.value, ' and the innerHTML is: ', button.innerHTML);
if (button.value == "UTC") {
button.value = "Local time";
console.log('Now the value has changed to: ', button.value, ' but the innerHTML has not: ', button.innerHTML);
button.innerHTML = "Local time";
console.log('The new value of the button is still: ', button.value, ' but now the innerHTML is also changed: ', button.innerHTML);
}
}
<button id="tz" type="button" value="UTC" onClick="changeValue(this);" name="button">UTC</button>
答案 1 :(得分:0)
对我有用的是利用事件绑定。根据Tyler Roper的建议,要使其在我的特定情况下能够正常工作,我要做的就是为按钮函数添加一个事件侦听器,并完全省略内联onclick事件。
checkboxlink_label
var btn = document.getElementById("tz");
function button() {
if (btn.value == "UTC") {
btn.value = "Local time";
} else {
btn.value = "UTC";
}
}
btn.addEventListener("click", button, false);