【问题标题】:Jquery not selecting proper href'sJquery没有选择正确的href
【发布时间】:2012-07-29 18:11:57
【问题描述】:

这个脚本:

$(function() {
    $('a').each(function() {
        var href = $(this).attr('href');
        if ("a:not(http://)") {
            $(this).attr('href', '/' + href);
        }
    });
});

为每个链接添加斜线,甚至包含“http://”的链接不知道为什么?我没有收到任何错误?

关于如何解决此问题的任何想法?

【问题讨论】:

  • 你希望if("a:not(http://)")做什么?
  • 你为什么要这样做?这将更新相对链接、SSL 链接、文件链接等...

标签: javascript jquery url href


【解决方案1】:

你把两件事搞混了:

  • jQuery 选择器:

    $(function() {
        $('a:not([href^="http://"])').each(function() {
            var href = $(this).attr('href');
            $(this).attr('href', '/' + href);  
        });
    });
    
  • 和纯javascript if 语句:

    $('a').each(function() {
       var href = $(this).attr('href');
       if (href.substr(0, 'http://'.length) == 'http://'){
           $(this).attr('href', '/' + href); 
       }   
    });
    

两者都做同样的事情。

请注意,它们将为 http 以外的其他方案生成无效链接(例如 /https://example.com/index.html)。根据您使用的 HTML 代码的干净程度,您可以简单地查找冒号来识别绝对链接:

$(function() {
    $('a:not([href*=":"])').each(function() {
        var href = $(this).attr('href');
        $(this).attr('href', '/' + href);  
    });
});

【讨论】:

    【解决方案2】:

    首先,你的代码等于下面的

    $(function() {
       $('a').each(function() {
          var href = $(this).attr('href');
          if(true) { $(this).attr('href', '/' + href); }   
       });
    });
    

    如果你真的想根据条件更新href,if语句应该不同:

    $(function() {
       $('a').each(function() {
         var href = $(this).attr('href');
         if(href.indexOf('http://') == -1 ) { $(this).attr('href', '/' + href); }   
       });
    });
    

    另一种方式是@Yogu 提供的方式,在这种方式中,您无需循环访问您不会更新的链接

    【讨论】:

      【解决方案3】:

      只是 Yogu 的一个插件,

      请记住,您在每个标签的上下文中。 “在对象本身内部”。 因此,您可以直接访问 href。

      $('a').each(function() {
         if (this.href.substr(0, 'http://'.length) == 'http://'){
             this.setAttribute('href', '/' + href); 
         }   
      });
      

      【讨论】:

        猜你喜欢
        • 2019-08-03
        • 2019-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-15
        • 2019-02-26
        • 1970-01-01
        • 2021-05-12
        相关资源
        最近更新 更多