gpt4 book ai didi

javascript - 如何仅通过替换一些文本来更改 href 标签

转载 作者:行者123 更新时间:2023-11-28 21:05:29 25 4
gpt4 key购买 nike

如果有人从 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://");
}
}
}

最佳答案

您正在使用 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);
}

关于javascript - 如何仅通过替换一些文本来更改 href 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com