当前位置:网站首页>Binding click events, when the click events rely on asynchronous return results, bubble failure will be prevented

Binding click events, when the click events rely on asynchronous return results, bubble failure will be prevented

2020-12-07 16:44:14 Bud and heart clear

background

In the development process , There is no problem with debugging to prevent bubbling , But the real use It's time to find that it's ineffective to stop bubbling , The original reason is that click events rely on asynchronous return results .

Normal stop bubble writing

<div class="aa notice">
    <div class="bb notice"></div>
</div>
<script>
    var arr = document.getElementsByClassName("notice");
    for(let i of arr){
        i.addEventListener("click",function (e) {
            console.log("i",i)
            //  To prevent a bubble 
            const ev = e || window.event;
            if (ev && ev.stopPropagation) {
                // Not IE browser 
                ev.stopPropagation();
            } else {
                //IE browser (IE11 following )
                ev.cancelBubble = true;
            }
        })
    }
</script>

Stop bubbling failure scenarios :

<div class="aa notice">
    <div class="bb notice"></div>
</div>
<script>
    var arr = document.getElementsByClassName("notice");
    for(let i of arr){
        i.addEventListener("click",function (e) {
            console.log("i",i)
            doReport(reportList, timeout).then(() => {
                //  To prevent a bubble 
                const ev = e || window.event;
                if (ev && ev.stopPropagation) {
                   // Not IE browser 
                   ev.stopPropagation();
                } else {
                   //IE browser (IE11 following )
                   ev.cancelBubble = true;
                }
            })
        })
    }
</script>

doReport It's a reporting method , Here, you need to wait for the submission to be completed before executing the click logic , It can lead to the failure of preventing bubbling .

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Bud and heart clear]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207164214472o.html