How to fires onClick event before onChange (even if the value has changed)?

穿精又带淫゛_ 提交于 2019-12-13 09:34:10

问题


Hello everyone and sorry for my english.

Following this jdfiddle, I have a problem I don't understand.

First I change the value of the input, then I click on the button and what I expected to see is "click" but I see "change" meaning onclick is called after onchange.

<input type="text" onChange="alert('change')" />
<button type="button" onClick="alert('click');">Click!</button>

I found on this post that it's because of chrome which fires onchange event before the onclick event. But I don't really have the same need as this post because my event are not declared in the same tag. And secondly, if I click on the button I would like to only execute the onclick function and not onclick and then onchange (this methods consists in using onMouseDown).

Do you have a good method to do that?


回答1:


Ok so I can see that you really wan't this. You could let the on change function run first, and then afterward see what has focus, if it is that button, you would know that it was clicked, and thus was the reason for loosing focus.

you cannot check this while the change function is running, as the body still has focus at this time..

<head>
  <script language="javascript">
  function focussed()
  {
    var triggerElement = document.activeElement
    alert(triggerElement)
    console.info(triggerElement)
  }

  function change()
  {
    alert("change")
    setTimeout(focussed, 1)
    return true
  }
  </script>

</head>
<body>
    <input type="text" onChange="alert('change')" />
    <button type="button" onClick="alert('click');">Click!</button>
</body>


来源:https://stackoverflow.com/questions/29254189/how-to-fires-onclick-event-before-onchange-even-if-the-value-has-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!