提问人:dc09 提问时间:11/15/2023 最后编辑:dc09 更新时间:11/15/2023 访问量:35
如何触发在通过jQuery之前附加的点击事件之前附加的点击事件?
How to fire click event that was attached later before click event attached earlier via jQuery?
问:
//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()
答:
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>
评论
[<>]
.on