当用户立即单击按钮时,按钮 onclick 在 onchange 输入字段后不会触发
我有一个带有 onchange 事件的输入文本,该事件调用一个显示警报框的函数。我还有一个按钮,其 onclick 调用不同的函数。如果用户更改输入文本并立即单击按钮,则会触发 onchange 事件,显示警报框,但按钮 onclick 函数中的代码不会执行。我读到这与事件冒泡有关,但我还没有看到任何解决方案。有解决办法吗?有可能吗?
下面是一个小示例:
<input type = "text" onchange = "showAlert1()">
<input type = "button" id = "al2" value = "Click Here" onclick = "showAlert2()">
<script type = "text/javascript">
function showAlert1()
{
alert("ONE")
}
function showAlert2()
{
alert ("TWO");
}
</script>
如果对输入值进行更改并且用户立即单击按钮,则 onclick 事件处理程序 showAlert2()
不会触发。 我希望,您在输入字段中写入一些内容,立即单击按钮,它会触发
alert("ONE")
和 alert("TWO")
...
或仅
警报(“两个”)
I have an input text with an onchange event that calls a function in which an alert box displays. I also have a button whose onclick calls a different function. If the user makes a change in the input text and immediately clicks the button, the onchange event fires, displaying the alert box, but the code in the function for the onclick of the button doesn't execute. I've read that this has something to do with event bubbling, but I haven't seen any solutions. Is there a solution? Is it even possible?
Here is a little example:
<input type = "text" onchange = "showAlert1()">
<input type = "button" id = "al2" value = "Click Here" onclick = "showAlert2()">
<script type = "text/javascript">
function showAlert1()
{
alert("ONE")
}
function showAlert2()
{
alert ("TWO");
}
</script>
The onclick event handler showAlert2()
doesn't fire if a change is made to the input value and user immediately clicks the button.
I want, that you write something to the input-field, click IMMEDIATELY the button and it fires
alert("ONE")
AND alert("TWO")
...
OR ONLY
alert("TWO")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,这不是冒泡的问题(这是 onchange 的问题,但在本例中是一个转移注意力的问题)。问题在于,更改字段值后单击按钮会触发
blur
,导致showAlert1()
在触发按钮的onclick
之前运行。这是一个按照您所描述的方式工作的简单示例,但您会发现它是一种不可靠的黑客行为。基本上,它缓冲每个函数的执行,以便可以触发按钮的
onclick
。但是,如果您单击并按住按钮的时间长于通过setTimeout()
在每个函数中设置的缓冲区,它就会崩溃。演示:jsfiddle.net/5rTLq
As far as I can tell it's not a problem with bubbling (which is a problem with
onchange
but is a red herring in this case). The problem is that clicking the button after changing the field value is triggeringblur
, causingshowAlert1()
to run before the button'sonclick
gets triggered.Here's a quick example of it working the way you described but you'll see it's an unreliable hack more than anything. Basically it buffers the execution of each function so that the button's
onclick
can be triggered. However it falls over if you click and hold the button longer than the buffer that is set within each function viasetTimeout()
.Demo: jsfiddle.net/5rTLq
这个测试怎么样
: http://jsfiddle.net/C3jRr/2/
how about this
test: http://jsfiddle.net/C3jRr/2/