父元素a标签的href默认行为以及子元素绑定的click事件的响应之间存在影响
生活随笔
收集整理的這篇文章主要介紹了
父元素a标签的href默认行为以及子元素绑定的click事件的响应之间存在影响
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文地址
背景
開發過程中遇到問題,簡單寫個demo 運行環境為Chrome 68
描述一下這個問題,當a標簽內部存在嵌套時, 父元素a標簽的href默認行為以及子元素綁定的click事件的響應之間存在影響。頁面結構:
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>a標簽內部點擊事件失效</title><style>* {margin: 0;padding: 0;}.father {display: block;width: 500px;height: 200px;background-color: rgb(210, 111, 30);}.child-one {display: block;width: 200px;height: 50px;background-color: rgb(174, 43, 226);}.child-two {display: block;width: 200px;height: 50px;background-color: rgb(43, 226, 67);}.child-three {display: block;width: 200px;height: 50px;background-color: rgb(43, 137, 226);}</style> </head><body><a class="father" href="father" onclick="alert(111)">父標簽<span class="child-one">子標簽1</span><object><a class="child-two" href="child-two">子標簽2</a></object><object><a class="child-three" href="javascript:alert('href:child-three')">子標簽3</a></object></a><script> let father = document.querySelector('.father');let ele1 = document.querySelector('.child-one');let ele2 = document.querySelector('.child-two');let ele3 = document.querySelector('.child-three');ele1.addEventListener('click', function (e) {e.stopPropagation();// e.preventDefault();alert('click child-one')window.location.href = 'child-one'}, false)ele2.addEventListener('click', function (e) {e.stopPropagation();alert('click child-two')// window.location.href='child-two'}, false)ele3.addEventListener('click', function (e) {alert('click child-three')window.location.href = 'child-three'}, false)father.addEventListener('click', function (e) {alert('click father')window.location.href = 'father'}, false)</script> </body></html>示例如下圖(如果a標簽嵌套,瀏覽器解析錯誤,所以用object標簽包裹了一層)。
執行操作:
說明onclick執行先于href
阻止冒泡后,執行結果仍然不符合預期。添加preventDefault之后,執行了子元素自己的跳轉。
上面4個操作除了2之外都很好理解,2中,為什么已經在阻止了事件冒泡之后,仍然執行了父元素中href的跳轉。
思考:
首先可以肯定的是,事件冒泡確實被阻止了,因為父元素的onclick并沒有執行。
所以猜測,<a>標簽的默認行為是無法通過取消冒泡來阻止的,就算事件沒有冒泡到父元素,子元素在父元素<a>標簽內部,仍然會執行<a>標簽默認行為。
解決方法:
- 在子元素中添加e.preventDefault()阻止默認行為
- 父元素不使用<a>標簽,使用其他標簽綁定click事件且子元素阻止冒泡
- 父元素不使用href屬性,直接在<a>標簽上綁定click事件
總結
以上是生活随笔為你收集整理的父元素a标签的href默认行为以及子元素绑定的click事件的响应之间存在影响的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 针对N=p^rq分解之初探
- 下一篇: 若依单体Vue版本新增多环境配置