单击时获取 href 的顶部主机名

Get the top host name of href on click

本文关键字:顶部 主机 href 获取 单击      更新时间:2023-09-26

>我有一个链接,我想在其中获取点击的域的顶级域名。在我的例子中,我有

    <a href="http://www.example.com/this/that">click on this link</a>

当我点击它时,我想要一个警报说

www.example.com

我知道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

而不是www.example.com

实现这一目标的最佳方法是什么?

实际上非常简单

,不需要正则表达式:

jQuery(document).on("click", "a[href]", function (event) {
    event.preventDefault();
    alert(this.hostname);
});

参见 MDN - HTMLAnchorElement。

我不确定它是否适用于IE浏览器。

尝试

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那样得到广泛的支持。