如何触发在通过jQuery之前附加的点击事件之前附加的点击事件?

How to fire click event that was attached later before click event attached earlier via jQuery?

提问人:dc09 提问时间:11/15/2023 最后编辑:dc09 更新时间:11/15/2023 访问量:35

问:

//First click handler added via a plugin whose files I do not wish to change
jQuery('.element').click(function(){
console.log('click event 1');
});

//2nd click handler - need this to be executed before the 1st 
jQuery('.element').click(function(e){
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="element">Click Here</div>

我有以下代码,将单击事件附加到某些元素:

$('.element').click(function(){
console.log('click event 1');
});

如果执行上述代码后,以下代码会将第二次单击事件处理程序附加到同一元素:

$('.element').click(function(e){
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
});

事件,尽管第二个代码块有,,第一个函数被执行。如何更改执行顺序,以便在点击事件中首先执行第二个代码块?event.preventDefault()event.stopPropagation()

javascript jquery jquery事件

评论

0赞 trincot 11/15/2023
如果不希望执行第一个单击处理程序,为什么不删除它呢?
0赞 dc09 11/15/2023
第一个块是通过插件添加的,我不想对插件文件进行更改。如果没有办法完成上述任务,这将是最后的选择。
0赞 mplungjan 11/15/2023
请使用片段编辑器显示一个最小的可重现示例。发布相关的 HTML、JS 和 CSS,然后单击左侧以获取 jQuery 框架。如果版本不存在,您可以编辑链接。[<>]
0赞 mplungjan 11/15/2023
还可以使用委托来处理此问题.on
1赞 CBroe 11/15/2023
如何对与jQuery绑定的事件进行排序有几个想法。

答:

0赞 mplungjan 11/15/2023 #1

因此,这不起作用,因为首先执行第一个事件处理程序

$('.element').on("click", function() {
  console.log('click event not under my control yet');
});

$("#container").on("click", ".element", function(event) {
  // Your logic here to decide whether to allow the original event handler
  var shouldAllowEvent = false /* your condition */ ;

  if (!shouldAllowEvent) {
    event.stopImmediatePropagation();
  }

  console.log('intercepted event')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="container">
  <a href="#" class="element">Click</a><br/>
  <a href="#" class="element">Click</a>
</div>

让我们把它关掉

$('.element').on("click", function() {
  console.log('click event not under my control yet');
});

// Step 1: Unbind the existing event handler
$('.element').off("click");

// Step 2: Bind YOUR event handler to the container
$("#container").on("click", ".element", function(event) {
  var shouldAllowEvent = false; // Your condition

  if (!shouldAllowEvent) {
    event.stopImmediatePropagation();
    console.log('Event intercepted and blocked');
  }
});

// Step 3: Re-bind the "original" event handler if you know it. If not, it is not trivial to get it back
$('.element').on("click", function() {
  console.log('click event NOW under my control');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="container">
  <a href="#" class="element">Click</a><br/>
  <a href="#" class="element">Click</a>
</div>