简体   繁体   中英

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

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).

用这个

$("#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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