【问题标题】:How to change the href tag by only replacing some text如何仅通过替换一些文本来更改 href 标签
【发布时间】:2017-08-26 20:11:37
【问题描述】:

如果有人从 iOS 调用该页面,我会尝试替换 href。问题在于 JavaScript 不仅替换了搜索到的文本,而且替换了所有初始链接。例如:

<a href="http://example.com" class='dynamicLink'>test</a>

当iOS手机或平板在此链接更改时

 <a href="http://ios+example.com" class='dynamicLink'>test</a>

但是 JavaScript 替换了所有

 <a href="http://ios+" class='dynamicLink'>test</a>

有人知道这个问题吗

window.onload = function changeLinks() {
    var href = "http://ios+"
    var links =
        document.getElementsByClassName('dynamicLink');
    if (navigator.userAgent.match(/Android/i) ||
        navigator.userAgent.match(/webOS/i) ||
        navigator.userAgent.match(/iPhone/i) ||
        navigator.userAgent.match(/iPad/i) ||
        navigator.userAgent.match(/iPod/i) ||
        navigator.userAgent.match(/BlackBerry/i) ||
        navigator.userAgent.match(/Windows Phone/i)
    ) {
        for (var i = 0; i < links.length; i++) {
            links[i].href = href.replace('http://', "http://ios+");
        }
    } else {
        for (var i = 0; i < links.length; i++) {
            links[i].href = href.replace('http://', "http://");
        }
    }
}

【问题讨论】:

  • 我不清楚你希望该代码做什么......对不起,但解释很混乱

标签: javascript jquery html ios


【解决方案1】:

您正在使用href.replace(... 替换链接,但href 上面定义为var href = "http://ios+"

试试这个方法:

for (var i = 0; i < links.length; i++) {
    links[i].href = links[i].href.replace('http://',"http://ios+");
  }

甚至这个,实际使用这个href

for (var i = 0; i < links.length; i++) {
    links[i].href = links[i].href.replace('http://', href);
  }

【讨论】:

  • 上帝保佑你非常感谢,我不知道问题出在哪里
猜你喜欢
  • 1970-01-01
  • 2013-09-05
  • 2022-08-20
  • 2015-11-19
  • 2020-04-06
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多