【问题标题】:Edit a portion of an attribute编辑属性的一部分
【发布时间】:2013-07-04 21:26:19
【问题描述】:

我需要更改链接的href,这样最后就不会说.com,而是说.net

$('selector').attr('href','http://example.com');

这是我目前正在使用的代码,但它只是替换了整个属性。我只希望它改变.com

有人可以修复我的代码以使其正常工作吗?我知道这是非常基础的,但我是 jQuery 的初学者。

【问题讨论】:

    标签: jquery attributes href


    【解决方案1】:

    可以使用attr的回调函数:

    $('selector').attr('href', function(_, href) {
        return href.replace('.com', '.net');
    });
    

    【讨论】:

      【解决方案2】:

      试试这个:

      var a = $('selector');
      a.attr('href', a.attr('href').replace('.com', '.net'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-15
        • 2021-09-12
        • 1970-01-01
        • 2012-11-29
        相关资源
        最近更新 更多