简体   繁体   English

我尝试在 html 中创建一个 On 和 Off 按钮,但是当我将标签输入放入表单时不起作用,它保持打开状态并不会切换到打开状态

[英]I try to make a On and Off button in html and but when I put the tag input inside the Form doesn't work it stay on off doesn't switch to On

I try to make a On and Off button in html and but when I put the tag input inside the Form doesn't work it stay on off doesn't switch to On我尝试在 html 中创建一个 On 和 Off 按钮,但是当我将标签输入放入表单时不起作用,它保持打开状态并不会切换到打开状态

 function onoff() { currentvalue = document.getElementById('onoff').value; if (currentvalue === "Off") { document.getElementById("onoff").value = "On"; } else { document.getElementById("onoff").value = "Off"; } }
 <form action="" method="post"> <input type="button" value="Off" id="onoff" onclick="onoff();" class="button button2"> </form>

You may just rename your function name to not match id of the clicked target and your code will work:您可以重命名您的函数名称以不匹配单击目标的id ,您的代码将起作用:

 function onoffHandler() { currentvalue = document.getElementById('onoff').value; if (currentvalue === "Off") { document.getElementById("onoff").value = "On"; } else { document.getElementById("onoff").value = "Off"; } }
 <form action="" method="post"> <input type="button" value="Off" id="onoff" onclick="onoffHandler();" class="button button2"> </form>

This happens because a legacy scope being injected into the scope chain.这是因为遗留作用域被注入作用域链。 But only for inline handlers .但仅适用于内联处理程序 That allows to address all your forms' elements having id or name attribute by the same variable names.这允许通过相同的变量名称处理所有具有idname属性的表单元素。 And since those id and name variables are in higher (closer) scope they shadow all other functions or variables with the same names.并且由于这些idname变量在更高(更近)的范围内,因此它们隐藏了所有其他具有相同名称的函数或变量。

If you need more thorough explanation what exactly is happening you may check out this [answer] ( https://stackoverflow.com/a/9160009/3388225 ).如果您需要更彻底的解释到底发生了什么,您可以查看这个 [answer] ( https://stackoverflow.com/a/9160009/3388225 )。

Try this:试试这个:

 <form action="" method="post"> <input type="button" value="Off" id="onoff" onclick="document.getElementById('onoff').value==='Off'?document.getElementById('onoff').value='On':document.getElementById('onoff').value='Off';" class="button button2"> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM