【问题标题】:How to change the target of any local link when clicked, using javascript / jquery?单击时如何使用javascript / jquery更改任何本地链接的目标?
【发布时间】:2010-10-20 08:02:26
【问题描述】:

点击任何本地链接时,我需要更改它的href。 我已经弄清楚如何选择正确的链接并创建新的 url,但不确定如何更改位置。我需要确定任何其他点击事件也已运行,因此我不能立即更改位置。

var my_host = 'example.com';
$(document).click(function(e) {
    if(e.target.hostname == my_host)
    {
        alert(e.target.protocol + "//" + e.target.hostname + "/#" + e.target.pathname + e.target.search);
        //...
    }
});

这和我的earlier question有关。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以像这样在本地链接上绑定事件并使用attr 方法更改href

    $('a[href*="yourdomain.com"]').click(function(){
      // your code before changing href
      $(this).attr('href', 'new url here');
    });
    

    yourdomain.com 替换为您自己的域,以便上述代码仅针对您的本地链接。

    【讨论】:

    • 谢谢。您已经回答了我的问题,并使代码更短。但是,您还引入了一个错误;如果域在路径中的其他位置,例如作为查询字符串中的返回 url,这将被错误地触发。
    • @SystemicPlural:您可以使用document.location.search 找到 url 内容并相应地提取部分。
    【解决方案2】:

    这是完全未经测试的,但应该能让你到达你要去的地方:

    var site = "http://yourdomain.com";
    
    // Match anchor tags with an href value that starts with your
    // site URL, or that start with / which are relative URLs (also
    // your site).
    $('a[href^="' + site + '"] a[href^="/"]').click(function(){
        var url = $(this).attr('href');
        if (url.indexOf(site) != -1) {
            url = site + "/#" + url.replace(site, ""); // Quick dirty way to get the path component of the URL
        } else {
            url = "/#" + url;
        }
        $(this).attr("href", url);
    });
    

    请注意,我阅读了您的另一个问题,但我个人不明白您为什么要在点击事件上执行此操作,而不是在页面加载后立即替换所有 href 值。

    【讨论】:

    • 这不适用于 https 链接。这样做的原因是,替换一个链接比替换几十个链接要少得多。此外,在我的情况下,内容是动态加载的 - 所以单一解决方案是理想的。
    • 以前的答案 1) 没用,2) 没有考虑相对 URL。您可以在我的代码中添加一些字符来处理 https 哈哈哈
    • P.S.不确定你在做什么,但如果你想让搜索引擎蜘蛛索引正确的 URL,你会想要更改所有的 URL(不仅仅是点击的 URL)。
    【解决方案3】:

    感谢 Sarfraz:这是没有错误的答案。

    var my_host = "example.com";
    $('a[href^="/"], a[href^="http://' + my_host + '"], a[href^="https://' + my_host + '"]').click(function(e){
        $(this).attr('href', e.target.protocol + "//" + e.target.hostname + "/#" + e.target.pathname + e.target.search);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多