【问题标题】:How can I make a userscript that changes every 'href' attribute of every element?如何制作一个更改每个元素的每个“href”属性的用户脚本?
【发布时间】:2015-10-15 10:24:46
【问题描述】:

我看过一个类似的问题,但是它获取了每个类的 href 属性,我想要每个元素的 href 属性。然后我想将其更改为我指定的一个链接。他们的解决方案如下所示:

var a,b,c,d, len;

a = document.getElementsByClassName("item title_link");
len = a.length;

    b = a[i].getAttribute('href');
    c = b.replace("#", "");
    d = "http://www.domainname.com/index/" + c + "/get";
    console.log(d); //just to check them out
}

//window.location.href = d;
//or whatever you wanted to do with that...

有什么方法可以替换每个属性而不是只替换指定的类?

【问题讨论】:

  • getElementsByTagName() 你在找什么?

标签: javascript jquery href userscripts


【解决方案1】:

纯Javascript方式:

var a = document.querySelectorAll("a");
[].forEach.call(a, function(elem){
  var b = elem.getAttribute('href');
  var newHref = "http://www.domainname.com/index/" +  b.replace(/#/g, '') + "/get";
  elem.setAttribute("href", newHref);
  console.log(newHref);
});

【讨论】:

    【解决方案2】:

    当您添加 jQuery 标记时,我假设您接受使用 jQuery 的答案。使用它非常简单,你只需要这样做:

    $("[href]").attr("href", "your desired href destination");
    

    Here 是一个带有示例的 jsfiddle。

    说明[href] 选择器选择所有具有href 属性的元素,.attr() 函数将其值替换为您想要的值。

    【讨论】:

    • 谢谢!如此简单高效!
    • 其实jQuery比内置函数效率要低一些,但我认为可读性损失一点点性能是值得的。
    【解决方案3】:

    以 jQuery 方式:

    items = $("a");
    
    $(items).each(function(index, item){
        b = $(item).attr('href');
        c = b.replace("#", "");
        d = "http://www.domainname.com/index/" + c + "/get";
        //console.log(d); //just to check them out
        item.attr('href', d);
    });
    

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 1970-01-01
      • 2016-01-24
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2017-10-31
      相关资源
      最近更新 更多