How to order the same element click event?

时间:2015-07-08 16:00:56

标签: javascript jquery

I have a page containing several different scripts, and there is some click event binding to the same element. So I encounter an issue with the event order. There is code. (for the more the script A and B is unknown).

I want execute Script A after Script B is executed.

//Script A
$('a').click(function (){
    alert('1')
})

//Script B
$('a').click(function (){
    alert('2')
})

Any advice? Thanks

1 个答案:

答案 0 :(得分:3)

假设您有两个脚本:script1.jsscript2.js。它们都将事件处理程序附加到同一元素。 script1.js目前已加载script2.js

现在,script1.js中的处理程序将在script2.js中的处理程序之前执行。有几种方法可以改变这种情况:

  1. 交换加载顺序。确保在script2.js
  2. 之前加载script1.js
  3. script1.js中的处理程序附加到唯一事件,并从script2.js触发。
  4. 示例:

    // script1.js
    $('a').on('custom-event', function(e) {
      // do stuff
    });
    
    // script2.js
    $('a').click(function(e) {
      // do stuff
      $(this).trigger('custom-event', e);
    });