【前端面试题】劫持页面所有a标签,在跳转前进行操作

首先提取关键信息所有a标签,那么考察的基本是事件委托没跑了。

事件委托,就是将事件绑定绑定到其父元素上,由父元素触发。

优点是不用给每个元素都绑定事件,而且无论是动态新增、删除的元素都可以绑定上事件,节省事件注册,节省内存

缺点是不是所有的事件都支持,而且如果页面dom层级嵌套过深,某一元素阻止了事件冒泡就会出现不可预知的问题

实现方法如下:

<a href="https://www.baidu.com/">点我跳转到百度</a>
<a href="https://juejin.cn/">点我跳转到掘金</a>
<a href="https://www.bilibili.com/">点我跳转到B站</a>
<a href="#">测试</a>

<script>
	const body = document.documentElement;
    body.addEventListener('click', e => {
      
      
        // 阻止默认事件,避免点击跳转
        e.preventDefault();
        const target = e.target;
        // 获取模板元素,只有点击的是a标签才劫持。只要能判断是a标签就行,这里用的localName
        if (target.localName === 'a') {
      
      
            // 获取到a标签上的链接
            const url = target.getAttribute('href');
            // 进行的操作。confirm返回一个布尔值,点了确定为true,否则为false
            if (confirm(`即将跳转到${ 
        url}`)) {
      
      
                window.open(url);
            }
        }
    });
</script>

猜你喜欢

转载自blog.csdn.net/qq_43398736/article/details/126797240
今日推荐