[英]Get the top host name of href on click
I have a link where I want to get the top level domain name of the domain clicked. 我有一个链接,我想在该链接中获得单击的域名的顶级域名。 In my example I have
在我的例子中
<a href="http://www.example.com/this/that">click on this link</a>
When I click on it I want an alert saying 当我单击它时,我想要一个警告说
www.example.com www.example.com
I know window.location.host does this for the actual location of the site but am not sure how to get this for the individual href I have tried the below but it returns 我知道window.location.host是针对网站的实际位置执行此操作的,但是不确定如何为单个href获取该位置,我尝试了以下操作,但返回了
jQuery(document).on("click", "a", function (event) {
event.preventDefault();
var id = jQuery(this).attr('href') || 'nohref';
alert(window.location.host);
alert(id);
});
http://www.example.com/this/that http://www.example.com/this/that
rather than www.example.com 而不是www.example.com
What is the best way to achieve this? 实现此目标的最佳方法是什么?
It's pretty straightforward actually, no need for regular expression: 实际上,它非常简单,不需要正则表达式:
jQuery(document).on("click", "a[href]", function (event) {
event.preventDefault();
alert(this.hostname);
});
See MDN - HTMLAnchorElement . 请参见MDN-HTMLAnchorElement 。
I'm not sure if it works in Internet Explorer though. 我不确定它是否可以在Internet Explorer中使用。
Try 尝试
jQuery(document).on("click", "a", function (event) {
event.preventDefault();
var id = jQuery(this).attr('href') || 'nohref';
var domain = id.match(/http[s]?\:\/\/(.*?)[\/$]/)[1]
alert(domain);
});
var domain = jQuery(this).attr('href').match(/^https?:\/\/([^\/]+)/);
if (domain != null && typeof domain[1]!='undefined')
domain = domain[1];
else
domain = '';
您可以尝试使用document.domain
,尽管它不如window.location.host
受到广泛支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.