最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery. click event doesn't work after change event? - Stack Overflow

programmeradmin1浏览0评论

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. Why is that? It seems that the change event is blocking the click 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. Why is that? It seems that the change event is blocking the click event?

Share Improve this question edited Sep 14, 2012 at 2:06 xdazz 161k38 gold badges253 silver badges278 bronze badges asked Sep 13, 2012 at 10:13 abikuabiku 2,2465 gold badges25 silver badges31 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 11

It is blocked by alert. Change alert to console.log you will find two events all fired.

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
  3. The input raises a change event, since it raised a blur and the value changed
  4. Your change event callback opens an alert(2)
  5. The documents loses focus since a new window appeared
  6. The link will never experience the click.

The solution is not to use alert (as xdazz proposed).

use this

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

onchange event fires only after the element is blurred. 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.

发布评论

评论列表(0)

  1. 暂无评论