【问题标题】:jquery change attributejQuery更改属性
【发布时间】:2010-04-16 15:47:53
【问题描述】:

我有 4 个链接,我需要更改 rel 属性中的 href 属性。 我知道我做不到,所以我试图从 href 属性中获取数据,设置一个新属性(rel),在其中插入数据,然后删除 href 属性。

基本上我正在这样做:

$('div#menu ul li a').each(function(){
        var lin = $(this).attr('href');
        $('div#menu ul li a').attr('rel',lin);
        $(this).removeAttr('href');


        })
    })

它有效,但它在我拥有的每个链接中设置相同的 rel 数据。

有什么帮助吗?

【问题讨论】:

  • $('div#menu ul li a') === $(this) 在您的匿名函数中,并且您有两组右大括号和括号。
  • 我什至没有注意到额外的“})”。伙计……我需要吃饭或睡觉。

标签: jquery attributes href rel


【解决方案1】:
$('div#menu ul li a').each(function(){
    var lin = $(this).attr('href');
    $(this).attr('rel',lin);
    $(this).removeAttr('href');
});

【讨论】:

    【解决方案2】:

    试试

    $('div#menu ul li a').each(function(){
        var lin = $(this).attr('href');
        $(this).attr('rel',lin);
        $(this).removeAttr('href');
    
    
        })
    })
    

    实际上并没有运行代码……但看起来应该可以解决问题。

    【讨论】:

    • 看来我被打了! +1 给你。
    【解决方案3】:

    变化:

    $('div#menu ul li a').attr('rel',lin);
    

    收件人:

    $(this).attr('rel',lin);
    

    【讨论】:

      【解决方案4】:

      你可能做错了“它”。 (意味着有更好的方法来做你正在尝试的事情)。

      只是回答你的问题:

      $('#menu ul li a').each(function(){
          var lin = $(this).attr('href');
          $(this).attr('rel',lin).removeAttr('href');
      });
      

      【讨论】:

        【解决方案5】:

        这是一个可靠的 jquery 解决方案:

        $(function() {
            $("a.selector").on("click", function() {
                var trigger = $(this.hash);
                trigger.removeAttr("id");
                window.location.hash = this.hash;
                trigger.attr("id", this.hash.replace("#",""));
                return false;
            });
        });
        

        【讨论】:

          【解决方案6】:

          这就是问题

          $('div#menu ul li a').attr('rel',lin);
          

          此行将更改应用于与您的选择器匹配的任何元素,在您的情况下 将匹配四个链接 --改用这段代码

          $('div#menu ul li a').each(function(){
                  var lin = $(this).attr('href');
                  $(this).attr('rel',lin);
                  $(this).removeAttr('href');    
                  })
              })
          

          【讨论】:

            猜你喜欢
            • 2014-07-21
            • 2020-06-15
            • 2013-02-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-01-09
            • 2019-01-03
            • 1970-01-01
            相关资源
            最近更新 更多