event.cancelBubble=true e.stopPropagation() 取消事件处理,阻止事件

<tr><a href="xxx">连接</a></tr>

如上结构,单击tr的时候跳转至另一页

<tr style="cursor:pointer" onmouseover="this.style.backgroundColor='gainsboro'" onmouseout="this.style.backgroundColor=''" onclick="return Click();">

function Click() {

    window.location.href = "xxx";

}

<a href="xxx">连接</a> 可更改为<a href="xxx" onclick="event.cancelBubble=true">连接</a>

这样可以避免单击a标签的同时也跳转至另一页面。onclick="event.cancelBubble=true" 取消事件处理。

否则单击a的同时会跳转另一页面。

解析:

取消事件冒泡,在 IE 的事件机制中,触发事件会从子元素向父元素逐级上传,就是说,如果子元素触发了单击事件,那么也会触发父元素的单击事件;event.cancelBubble=true;可以停止事件继续上传

补充一点,Ie的事件传递是从下到上的:

事件来源对象->上级对象->上上级对象->.....->body->document->window

NS的事件传递是从上到下:

window->document->body->....->事件来源对象

(event.returnValue=false 设置事件的返回值为false,即取消事件处理)

2、两个事件区别

e.cancelBubble=true;// ie下阻止冒泡

e.stopPropagation();// 其它浏览器下阻止冒泡

stop propagation 语气比较正规,严肃;意译为“停止传播”
cancel bubble 语气比较口语化,近似聊天;意译为“取消冒泡”,也就是不要闲言碎语。

其实现在IE在遵守W3C标准下,两个事件都可以阻止事件冒泡。

我在实际工作中运用如下

//直接写在HTML里
 <a target="_blank" onclick="event.cancelBubble=true;" href='{:url("$classuri/printing_in")}?id={$vo.id}'>打印</a>


//写在js里
<a data-myhref='{:url("$classuri/info")}?id={$vo.id}' onclick="td_click(this,event);">{$vo.billcode}</a>

 function td_click(obj,ev){
        layer.open({
            title: '查看详情', type: 2, area: ['800px', '650px'], fix: true, maxmin: false, content: $(obj).data("myhref"),offset: '100px'
        });
        var e=(ev)?ev:window.event;
        if (window.event) {
            e.cancelBubble=true;// ie下
        } else {
            e.stopPropagation();// 其它浏览器
        }
    }

猜你喜欢

转载自blog.csdn.net/u011383596/article/details/83146167
今日推荐