单击子元素也会在其父元素上触发单击事件 [英] clicking on child element also triggers click event on it parent
问题描述
场景
我的主干应用程序中的视图由几个 boxes(它们是 div 元素)
组成.当用户单击一个框并按住鼠标按钮 500 毫秒时,我想在左上角显示一个 delete
按钮.当用户点击其他任何地方 #wrapper
时,delete
按钮应该隐藏.
My view in my backbone app consists of several boxes(which are div elements)
. When user clicks on one box and hold down the mouse button for 500 millisecond, then I want to show a delete
button on top left corner. When user clicks on anywhere else #wrapper
then that delete
button should hide.
问题
所以显示 delete
按钮不是问题.当我单击并按住一秒钟时,它确实显示删除按钮,它显示删除按钮半秒然后隐藏.它隐藏是因为我还在其父元素 #wrapper
中添加了 click 事件,它实际上隐藏了这个删除按钮.
So showing delete
button is not the issue. It does show delete button when I click and hold for a second it shows delete button for half a second then hides. It hides because I am also adding click event to its parent element #wrapper
which actually hides this delete button.
问题
当我点击并按住子元素 box
时,如何阻止父元素 #wrapper
触发点击事件?
So how can I stop parent element #wrapper
from triggering click event when I am clicking and holding down on child element box
?
这是我的代码
这里是父元素模块的代码
Here is the code for parent element module
var Boxes = Backbone.View.extend({
el: '#wrapper',
events: {
'click': 'method' //when clicked on wrapper i.e. parent of box trigger method function
},
render: function (PaintBoxModel) {
var paintBoxView = new PaintBoxView({ model: PaintBoxModel });
this.$el.find('#contents').append(paintBoxView.render().el);
return this;
},
method: function () {
console.log('method');
App.Vent.trigger('bodyclicked'); //trigger an event
}
});
这里是子元素的模块
var Box = Backbone.View.extend({
events: {
'mousedown': 'mouseHoldDown',
'mouseup': 'removeMouseHoldDown'
},
initialize: function () {
this.timeoutId = 0;
App.Vent.on('bodyclicked', this.removeDeleteBtnShadow.bind(this)); //here I am listening to the click event when parent `#wrapper` is clicked
},
mouseHoldDown: function () {
this.timeoutId = setTimeout(this.addDeleteBtnShadow.bind(this), 500);
},
removeMouseHoldDown: function () {
clearTimeout(this.timeoutId);
},
addDeleteBtnShadow: function () {
this.$el.append('<a href="#" class="remove">X</a>');
this.$el.addClass('is-shadow');
},
removeDeleteBtnShadow: function () {
this.$el.find('.remove').remove();
this.$el.removeClass('is-shadow');
}
});
推荐答案
Pass event
作为参数并使用 .stopPropagation()
.
Pass event
as argument and use .stopPropagation()
.
removeMouseHoldDown: function (e)
{
e.stopPropagation();
}
这篇关于单击子元素也会在其父元素上触发单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!