当onchange刚刚触发时,onclick事件未触发 [英] onclick event not triggered when onchange triggered right before

查看:233
本文介绍了当onchange刚刚触发时,onclick事件未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个有趣的问题.

i have a funny problem here.

我有一个文本区域,其中链接了一个onchange事件. 然后,我有一个链接到onclick事件的按钮.

I have a textarea with an onchange event linked to it. Then i have a button linked to an onclick event.

当在文本区域上触发onchange事件时,将处理放入文本区域的文本.当我单击文本区域之外的内容时,通常会发生这种情况.

The text being put to the textarea is processed when the onchange event gets triggered on the textarea. This normally happens when i click something outside of the textarea.

我所做的是以下事情:

  1. 我在文本区域中输入了文字.
  2. 输入后,我立即点击按钮以触发按钮上的onclick事件
  3. 什么都没有发生,但是当我单击按钮时,textarea的onchange事件被触发,但是按钮本身的onclick事件却未被触发.

为什么?我希望同时触发onchange和onclick.我有什么需要做的,因此单击按钮不会丢失".我意识到我必须单击两次,因为第一次单击会导致文本区域发生onchange,然后第二次单击会触发按钮的onclick.

Why? I expected to get both onchange and onclick triggered. Is there anything i need to do so the click on the button doesnt get "lost". I realized i have to click twice, because first click causes onchange on textarea, and THEN the second click triggers onclick on the button.

下面的代码显示了一个范例,只需尝试下面的代码即可.输入文本,然后直接单击该按钮.只有"textarea"弹出窗口会出现.

The code below shows an exmaple, just try the code below. Type in a text, then directly click on that button. Only the "textarea" popup will come up.

<textarea onchange="processText();" name="mytext"></textarea>
<button onclick="processButton();">Hello</button>
<script language="Javascript">
  function processText()
  {
    alert( 'textarea');
  }

  function processButton()
  {
    alert( 'button');
  }
</script>

推荐答案

您需要重新检查您的假设.在您的示例中, alert()中断了程序流,破坏了 onclick 的处理.这段代码( jsfiddle在这里)说明 onchange 不会干扰 onclick 默认情况下:

You need to recheck your assumptions. In your example, alert() interrupts the program flow, breaking handling of onclick. This code (jsfiddle here) demonstrates that onchange does not interfere with onclick by default:

<textarea onchange="processText();" name="mytext"></textarea>
<button onclick="processButton();">Hello</button>
<div id="clicked"></div>
<div id="changed"></div>
<script language="Javascript">
  function processText()
  {
    document.getElementById('changed').innerHTML = "onchange fired";;
  }

  function processButton()
  {
    document.getElementById('clicked').innerHTML = "onclick fired";
  }
</script>​

我有一个类似的问题,但是未处理 onclick 事件的实际原因是由于 onchange 处理程序而导致被单击的元素向下滚动.释放鼠标按钮时,该元素没有收到 mouseup 事件,并且单击"被中断.

I had a similar problem, but the actual reason that the onclick event was not handled was that the element being clicked, scrolled down as a result of the onchange handler. When the mouse button was released, the element did not receive a mouseup event and the "click" was interrupted.

这篇关于当onchange刚刚触发时,onclick事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆