gpt4 book ai didi

jquery 在右键单击事件中获取 元素的主机名

转载 作者:行者123 更新时间:2023-12-01 08:41:53 25 4
gpt4 key购买 nike

我想在右键单击或元素时获取 href 的扩展名和主机名。我已经尝试了下面的代码,但我得到“未定义”

$(document).mousedown(function(e) {
if (e.which == 3) {

var tag = e.target.nodeName;
var href = e.target.href;

if (tag == 'A') {
thelink = e.target.href;
console.log(href.hostname);

}
if (tag == 'IMG') {
thelink = e.target.src;
console.log(href.hostname);
}
}
});

最佳答案

您可以引用:

The URL interface represents an object providing static methods used for creating object URLs..

$(document).mousedown(function(e) {
if (e.which == 3) {
var tag = e.target.nodeName;
var thelink = undefined;

if (tag == 'A') {
thelink = e.target.href;

}
if (tag == 'IMG') {
thelink = e.target.src;
}

//
// if thelink then get the hostname...
//
if (thelink) {
//
// convert string to URL
//
var url = new URL(thelink);
console.log(url.hostname);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://dummyimage.com/200x200/000/fff">

关于jquery 在右键单击事件中获取 <a> 元素的主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46133445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com