我试图通过单击鼠标左键获取链接(可点击元素的 URL),下一个方法不适用于所有元素:
function callback(e) {
if (e.button != 0 ) {
return;
}
alert(e.target.href);
}
document.addEventListener('click', callback, true);
例如,对于 Youtube 网站上的某些元素 - 标题或缩略图(所有这些元素都是可点击的,并且它们会导致一些视频/播放列表):
href 为 undefined
但它是可点击的,并且 Google Chrome 浏览器会显示该元素所指向的链接的预览:
更新
Youtube 网站上的某些 A 标签将其他元素包裹在其中的问题:<a href="..."><span>...<span/><div.......></a>
我尝试了 Debug模式(检查),选择了其中一些元素进行检查,它选择了 <span>
<a>
里面.
其他解决方案:https://jsfiddle.net/z2huqjjh/2/ (如果链接(A 标签)动态添加到页面,这将是一个很好的解决方案)
最佳答案
默认情况下,事件会冒泡。这意味着您可以有一个元素嵌套在 100 个其他元素中。单击该嵌套元素将导致 click
事件,并且该事件将通过所有祖先元素向上传播,直到它被取消或到达 window
。
现在,几乎 document
中的所有内容是可点击的。仅仅因为某些内容可点击并不意味着它会导航到某个 URL,例如 <a>
元素确实如此。
例如:
document.querySelector("div").addEventListener("click", function(){
alert("Thanks for clicking me!");
});
<div>I'm a <div> and I don't have an 'href'. But, click me anyway</div>
因为只有少数元素实际上具有 href
属性,您可以更改代码以仅查看这些:
function callback(e) {
if (e.button != 0 ) {
return;
}
alert(e.currentTarget.href);
}
// Get all the anchors and place into an array
var anchorArray = Array.from(document.querySelectorAll("a"));
// Loop through the anchors
anchorArray.forEach(function(anchor){
// Assign a click event handler to each. When the click event
// bubbles to the element, the callback will be called
anchor.addEventListener('click', callback);
});
<div>I'm a div - click me anyway</div>
<a href="#"><span>I'm a span inside of an anchor, click me too!</span></a>
关于javascript - 某些可点击元素的未定义 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47211506/