Javascript 使用 addEventListener 或其他方法定义要在 onclick 事件上首先调用的函数

Javascript define function to be invoked first on onclick event using addEventListener or other method

我有遗留的 js 代码,我不去触及脚本中定义的内容 A.js .. 它有简单的 onlick 事件和功能附加到它

$(document).ready(function () {
    //jquery onclick 
    $("#create_button").click(function (e) {
    ..... 
    }
}    
    //html
     <button class="btn btn-primary" id="create_button"
                                            name="create_button">
                                        Create New app
                                    </button>

然后向我定义的这个按钮添加功能是在我的第二个脚本 B.js 中加载,它位于 A.js

之后
$(window).on('load', function(){
    document.getElementById("create_button").addEventListener("click", () => {
                                      self.MyFirstFunction()
                     }, false);

}

我的问题是如何定义 self.MyFirstFunction() 总是先触发?

您可以设置 eventListeneruseCapture 标志,使其具有高于其他 eventListeners 的最高优先级。

你的情况:

scriptB.js

$(window).on("load", function () {
    document
        .getElementById("create_button")
        .addEventListener("click", () => self.MyFirstFunction(), true);
});

演示:

let button = document.querySelector("#button")

button.addEventListener("click", () => {
  console.log("I was added first")
})

button.addEventListener("click", () => {
  console.log("I was added second")
}, true)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">Demo Button</button>

在向元素添加事件侦听器时将 useCapture 设置为 true:

For event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases. Event listeners in the “capturing” phase are called before event listeners in any non-capturing phases.

$('#element').click(function(){
  console.log("first registered Handler in source code")
})

document.getElementById("element").addEventListener("click",function(e){
console.log("second registered Handler in source code")},true); // Notice the last argument is true 
#element{
  width:200px;
  height:100px;
  background:lightgreen;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element"></div>