简体   繁体   English

jQuery的。更改事件后,click事件不起作用?

[英]Jquery. click event doesn't work after change event?

Having this sample code: 有这个示例代码:

<input type="text" id="changeid">
<a href="#" id="clickb">click</a>

<script>
    $('#clickb').on("click", function(event){
        alert(1);                             
        return false;
    });

    $('#changeid').on("change", function(event){
        alert(2);                             
        return false;
    });
</script>

When putting something into the text field and click the link immediately, only onchange event fires, but not link click event. 将某些内容放入文本字​​段并立即单击链接时,仅触发onchange事件,但不会触发链接单击事件。 Why is that? 这是为什么? It seems that the change event is blocking the click event? 似乎更改事件阻止了click事件?

It is blocked by alert . 它被alert阻止。 Change alert to console.log you will find two events all fired. alert更改为console.log您会发现两个事件都被触发。

The demo. 演示。

$('#clickb').on("click", function(event){
    console.log(1);
    return false;
});

$('#changeid').on("change", function(event){
   console.log(2);                             
   return false;
});​

When you edit the input and then click on the link the following happens on the inside 编辑输入然后单击链接时,内部会发生以下情况

  1. You start clicking on the 'link'. 您开始点击“链接”。 No events are generated yet (not even mousedown), because first the browser will do some cleanup work: 还没有生成任何事件(甚至没有生成),因为首先浏览器会做一些清理工作:
  2. The input loses focus and will raise a blur event 输入失去焦点并将引发blur事件
  3. The input raises a change event, since it raised a blur and the value changed 输入引发change事件,因为它引发blur并且值已更改
  4. Your change event callback opens an alert(2) 您的change事件回调会打开alert(2)
  5. The documents loses focus since a new window appeared 自出现新窗口以来,文件失去了焦点
  6. The link will never experience the click . 该链接永远不会遇到click

The solution is not to use alert (as xdazz proposed). 解决方案不是使用alert (如xdazz提议的那样)。

用这个

$("#changeid").live('change', function () ...

onchange event fires only after the element is blurred. onchange事件仅在元素模糊后触发。 So when u type some text and click on the link first the element is blurred on the text field. 因此,当您键入一些文本并首先单击链接时,元素在文本字段上模糊。 The best way to handle the change event on having onkeyup event to track the changes made on the text field. 使用onkeyup事件处理更改事件的最佳方法是跟踪对文本字段所做的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM