[英]Creating button in javascript, but onclick function automatic works
I am creating a button in javascript, but the onclick
function apply to the button
will automatically work even though I didn't click the button
.我正在 javascript 中创建一个按钮,但是即使我没有单击该button
,应用到该button
的onclick
function 也会自动工作。 Here is an example:这是一个例子:
//Ignore the code will keep increasing buttons and other kinds. This is just an example I quickly made that similar to my actual code function typing() { var btn = document.createElement('button') btn.innerHTML = "↓Show more"; btn.id = "textbutton" function display() { btn.innerHTML = 'closed' } btn.onclick = display() document.body.appendChild(btn) }
<textarea oninput="typing()"></textarea>
The innerHTML
of the buttons
in the above example created will automatically be closed
even though I didn't click it.上例中创建的buttons
的innerHTML
将自动closed
,即使我没有单击它。
Could anyone tell me why this happens and give me a better solution?谁能告诉我为什么会发生这种情况并给我一个更好的解决方案? Thanks for any responds!!!谢谢大家的回复!!!
It's happening because of this line:这是因为这条线而发生的:
btn.onclick = display()
That's taking the result of calling display()
and setting it as the onclick
handler for btn
.这是调用display()
并将其设置为btn
的onclick
处理程序的结果。
To fix it, just remove the parens:要修复它,只需删除括号:
btn.onclick = display
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.