我想使用stopImmediatePropagation来阻止同一元素上的第二个(mousedown)事件处理程序触发,但它不起作用。代码示例:
$(function() {
var showEventsMessage = function(options) {
options = $.extend({
eventType: 'CLICK',
eventTarget: this,
suffix: '<br>'
}, options);
var message = options.eventType + ': ' +
(options.eventTarget.nodeName || 'unknown') +
options.suffix;
$('#Messages').append(message);
}
$('.clickable').click(function() {
showEventsMessage.call(this, {
eventType: event.type
});
}).dblclick(function() {
showEventsMessage.call(this, {
eventType: event.type
});
}).mousedown(function() {
showEventsMessage.call(this, {
eventType: event.type
});
event.stopImmediatePropagation();
event.preventDefault();
}).mousedown(function() {
showEventsMessage.call(this, {
eventType: event.type,
suffix: '#2<br>'
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='clickable'>CLICK HERE ...
<p class='clickable'>or here!</p>
</div>
<div id="Messages"></div>
然而,如果我在调用stopImmediatePropagation的事件处理程序中添加一个event参数(请参见代码中带有“ARGUMENT ADDED HERE”的行),它确实可以正常工作!由于event是一个全局对象,这是如何可能的?我不明白到底发生了什么变化...!? 代码示例:
$(function() {
var showEventsMessage = function(options) {
options = $.extend({
eventType: 'CLICK',
eventTarget: this,
suffix: '<br>'
}, options);
var message = options.eventType + ': ' +
(options.eventTarget.nodeName || 'unknown') +
options.suffix;
$('#Messages').append(message);
}
$('.clickable').click(function() {
showEventsMessage.call(this, {
eventType: event.type
});
}).dblclick(function() {
showEventsMessage.call(this, {
eventType: event.type
});
}).mousedown(function(event) /* ARGUMENT ADDED HERE */ {
showEventsMessage.call(this, {
eventType: event.type
});
event.stopImmediatePropagation();
event.preventDefault();
}).mousedown(function() {
showEventsMessage.call(this, {
eventType: event.type,
suffix: '#2<br>'
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='clickable'>CLICK HERE ...
<p class='clickable'>or here!</p>
</div>
<div id="Messages"></div>