所以我在列表行中有一个按钮,用于从页面中删除该行(调用ajax东西来删除该行代表的对象,但这对我的问题并不重要)。整行绑定(bind)到一个单击事件,该事件将重定向到另一个页面。
换句话说,包含行是单击绑定(bind)的,内部按钮是单击绑定(bind)的,这给我带来了问题,因为单击内部按钮也会触发包含行单击事件(正如它应该的那样)。
我尝试为所有删除按钮绑定(bind)一个悬停事件,以解除鼠标悬停时的行单击的绑定(bind),并在鼠标移出时重新绑定(bind)它,如下所示的伪代码:
$('.delete-button').hover(
function() {
$('.list-row').unbind();
$('.delete-button').bind('click', function() { /* delete action */ });
},
function() {
$('.delete-button').unbind();
$('.list-row').bind('click', function() { /* list row action */ });
}
);
这效果不太好,但我相信有更好的方法来实现它。我应该将按钮从包含的列表行中取出吗?将其放在那里要容易得多,因为我的列表行包含自定义属性,其中包含 ajax 调用所需的数据,我只需 var rod = $('.delete-button).parent().attr(' row-id');
来获取数据,但我不反对更改:)
谢谢!
最佳答案
在按钮的点击事件处理程序中,您需要调用e.stopPropagation()
。这将防止事件在 DOM 树中冒泡。更多信息请点击:http://api.jquery.com/event.stopPropagation/
编辑:您已经接受(谢谢!),但也许这个代码片段将有助于更好地解释一些概念:
$('.list-row').click(function() {
/* list row action */
});
$('.delete-button').click(function(e) {
// die, bubbles, die
e.stopPropagation();
// if you also need to prevent the default behavior for the button itself,
// uncomment the following line:
// e.preventDefault();
// note that if you are doing both e.stopPropagation() AND e.preventDefault()
// you should just `return false;` at the end of the handler (which is jQuery-
// sugar for doing both of these at once)
/* delete action */
})
关于javascript - jQuery 对包含 div 和按钮的不同绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7362566/