iT邦幫忙

1

網頁前端JAVASCRIPT如何將網頁中所有連結增加變數

com 2022-04-08 14:31:212092 瀏覽
  • 分享至 

  • xImage

我想要將網頁內所有的超連結增加GET的變數【get=1】
例如

<a href="https://www.xxx.com/index.php?get=1">

我會加上【?get=1】
但是有些連結本身已經有其他變數
例如

<a href="https://www.xxx.com/index.php?other=1">

我的JAVASCRIPT原本寫法會變成

<a href="https://www.xxx.com/index.php?other=1?get=1">

要如何寫才能針對原本已經有變數的網址改成&get=1

<a href="https://www.xxx.com/index.php?other=1&get=1">
小魚 iT邦大師 1 級 ‧ 2022-04-11 21:13:17 檢舉
你寫了那麼多,
還是沒有人知道你怎麼寫的 XD
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
純真的人
iT邦大師 1 級 ‧ 2022-04-08 15:42:07
最佳解答

你參考吧~

<script type="text/javascript">
    function LinkOn() {
      var Str = "get=1";
      var A = document.getElementsByTagName("a");
      for (var i = 0; i < A.length; i++) {
        if (A[i].getAttribute("href").indexOf("?") > 0) {
          A[i].href += "&";
        } else {
          A[i].href += "?";
        }
        A[i].href += Str;
      }
    }
</script>

<button onclick="LinkOn()">連結加上參數</button>
<br /><br /><a href="https://www.xxx.com/index.php">測試1</a>
<br /><a href="https://www.xxx.com/index.php?other=1">測試2</a>
com iT邦新手 4 級 ‧ 2022-04-09 20:57:51 檢舉

感謝前輩使用最基礎的方式教學。
我融合了froce前輩的寫法

<script type="text/javascript">
	function LinkOn() {
		var A = document.getElementsByTagName("a");
		for (var i = 0; i < A.length; i++) {
			var testUrl = new URL(A[i].href);
			testUrl.searchParams.append("get", "1");
			A[i].href = testUrl.toString();
		}
	}
</script>

<button onclick="LinkOn()">連結加上參數</button>
<br /><br /><a href="https://www.xxx.org/index.php">測試1</a>
<br /><a href="https://www.xxx.org/index.php?other=1">測試2</a>

主要是依據您的寫法,每按一次,連結的網址就會增加相同變數一次變成【?get=1&get=1】,不過不影響功能。

2
海綿寶寶
iT邦大神 1 級 ‧ 2022-04-08 14:38:42

我想要將網頁內所有的超連結增加GET的變數【get=1】
我會加上【?get=1】

改成
加上&get=1
即可

就算前面沒有別的參數https://www.google.com/search?&q=ithelp 也不會錯

com iT邦新手 4 級 ‧ 2022-04-08 14:52:40 檢舉

前輩您好~感謝您的回答。
如果網址本身沒有帶變數&get=1很像又沒有作用,針對沒帶變數的網址應該怎麼寫比較好?

小山丘 iT邦新手 2 級 ‧ 2022-04-08 15:19:18 檢舉

海綿大說了阿,你就直接加上?&get=1

5
froce
iT邦大師 1 級 ‧ 2022-04-08 15:05:57

用js的URL物件,舊瀏覽器應該不支援:
https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams

let testUrl = new URL("https://www.xxx.com/index.php")
testUrl.searchParams.append("test", 1)
testUrl.searchParams.append("test2", 2)
console.log(testUrl.toString())

這篇正解, 推

小山丘 iT邦新手 2 級 ‧ 2022-04-08 15:26:40 檢舉

這方法最好

com iT邦新手 4 級 ‧ 2022-04-09 20:59:01 檢舉

感謝前輩提供方向。

0
天黑
iT邦研究生 5 級 ‧ 2022-04-08 15:09:07

取得所有tag a element,判斷href內容有?就是用&沒有就是?,用RegExp效能可能會好一點,可以試試看

0

很簡單
你先判斷是否有 ?
如果沒有就用該寫法:?get=1
如果有就用此寫法:&get=1

我要發表回答

立即登入回答