Prevent bubbling (default) events (IE8 compatible)

See the following HTML code:

 

<div onclick="parentClicked()">
    click i (parent element)
    <div onclick="childClicked()">
        click me (child element)
    </div>
</div>
<script>
function childClicked(event) {
    alert('child clicked');
}
function parentClicked(event) {
    alert('parent clicked');
}
</script>

 

After the above code runs, click the " click me (child element) " text, and you will find that not only the parent clicked prompt will pop up, but also the child clicked prompt will pop up. This is the bubbling problem when js manipulates HTML Dom elements. Regarding the bubbling problem, you can read related articles on Baidu, such as http://www.jb51.net/article/42492.htm.

 

Here, if we want to prevent the bubbling event, we often use the event.stopPropagation() method to prevent the event from bubbling to the parent element. But this method does not work in IE8. In IE8, you need to use to prevent bubbling, so there are the following wrapper functions:

 

function stopBubble (e) {
    // If an event object is provided, this is a non-IE browser
    if ( e && e.stopPropagation ) {
        // so it supports the W3C stopPropagation() method
        e.stopPropagation();
    } else {
        // Otherwise, we need to use IE's way to cancel event bubbling
        window.event.cancelBubble = true;
    }
}

 

 

By the way, blocking the default event also has this problem. The following code realizes that clicking on the A label will not jump:

 

<a href="www.baidu.com" onclick="clicked()">Click me will not jump</a>
<script>
function stopDefault( e ) {
     // Prevent default browser action (W3C)
     if ( e && e.preventDefault ) {
         e.preventDefault();
     } else {
        // The way to prevent the default action of the function in IE
        window.event.returnValue = false;
    }
    return false;
}
function clicked(event) {
    stopDefault(event);
    alert("I blocked the default event of clicking on the A label");
}
</script>

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327091017&siteId=291194637