简体   繁体   English

使用.getElementByID时,Onclick函数仅工作一次

[英]Onclick function only works once, when using .getElementByID

Other similar questions like this have been asked before, but the answer is usually that some variable is not being updated properly and therefore the button yields the same results each time. 之前也曾问过其他类似的问题,但答案通常是某些变量未正确更新,因此按钮每次都会产生相同的结果。 I have an html page with two text boxes, and a button between them which when clicked, takes in text from the topmost box, modifies it, and the modified text is then displayed in the bottom box. 我有一个带有两个文本框的html页面,它们之间有一个按钮,当单击它们时,它们将从最上面的框中输入文本,对其进行修改,然后在底部的框中​​显示修改后的文本。 Why does the function work only once even when new text is placed in the box? 为什么即使将新文本放入框中,该功能也只能运行一次?

 document.getElementById('buttonVal').onclick = function(){ var text = document.getElementById('textbox').value; var revText = document.getElementById('buttonVal').onclick = reverse(text) document.getElementById('revBox').value = revText }; function reverse(textString){ return textString.split("").reverse().join(""); } 
 <form> <fieldset> <legend>text reversal</legend> <p> Enter text in box below <p> <label></label> <textarea id = "textbox" rows = "10" cols = "120"></textarea> <br> <p> <input type="BUTTON" value="REVERSE" id="buttonVal"> <br> <p> Your text backwards is: <p> <label></label> <textarea id = "revBox" rows = "10" cols = "120"></textarea> </fieldset> </form> 

Very easy fix: 很容易解决:

change this 改变这个

var revText = document.getElementById('buttonVal').onclick = reverse(text)

to this 对此

var revText = reverse(text);

That first line is more or less gibberish. 第一行或多或少是乱码。

The issue is that you are using onclick inside an onclick method. 问题是,你正在使用onclickonclick方法。 If you just simplify that line from var revText = document.getElementById('buttonVal').onclick = reverse(text) (Which is also bad because you are doubly assigning something, one of which is an onclick method) to just var revText = reverse(text); 如果只是从var revText = document.getElementById('buttonVal').onclick = reverse(text)简化这一行(这也是很糟糕的,因为您要加倍分配某些东西,其中之一是onclick方法)到var revText = reverse(text); you can avoid some complexity and make the code work. 您可以避免一些复杂性并使代码正常工作。

 document.getElementById('buttonVal').onclick = function(){ var text = document.getElementById('textbox').value; var revText = reverse(text); document.getElementById('revBox').value = revText; }; function reverse(textString){ return textString.split("").reverse().join(""); } 
 <form> <fieldset> <legend>text reversal</legend> <p> Enter text in box below <p> <label></label> <textarea id = "textbox" rows = "10" cols = "120"></textarea> <br> <p> <input type="BUTTON" value="REVERSE" id="buttonVal"> <br> <p> Your text backwards is: <p> <label></label> <textarea id = "revBox" rows = "10" cols = "120"></textarea> </fieldset> </form> 

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

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