之前触发 onchange 时未触发 onclick 事件

onclick event not triggered when onchange triggered right before(之前触发 onchange 时未触发 onclick 事件)

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

问题描述

我有一个有趣的问题.

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

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

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

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.有什么我需要做的,所以点击按钮不会丢失".我意识到我必须单击两次,因为第一次单击会导致 textarea 上的 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 here)表明 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 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:之前触发 onchange 时未触发 onclick 事件

基础教程推荐