[英]How to change the href tag by only replacing some text
如果有人從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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.