簡體   English   中英

查找url是否包含href中url的特定部分並獲取完整鏈接或替換為另一個

[英]find if url contain specific part of url in href and get the full link or replace with another

如果可能的話,我需要在Javascript中完成此操作……這是解釋...

我在頁面上有幾個這樣的樣式表鏈接

<link rel="stylesheet" href="http://example.com/theme/themered/themered.css" type="text/css" media="all" />
<link rel="stylesheet" href="http://example.com/basic/basic.css" type="text/css" media="all" />
<link rel="stylesheet" href="http://example.com/default/style.css" type="text/css" media="all" />

並選擇帶有約50個主題CSS選項的HTML標簽,但此處僅添加2個

<select>
<option value="http://example.com/theme/themeblue/themeblue.css">Theme Blue</option>
<option value="http://example.com/theme/themegreen/themegreen.css">Theme Green</option>
<option value="http://example.com/theme/themeorange/themeorange.css">Theme Orange</option>
</select>

現在,我需要從javascript中進行選擇,例如從選擇下拉列表中選擇“ Theme Blue”,以腳本查找特定的樣式表,帶有標記名鏈接且帶有href的樣式表包含字符串“ http://example.com/theme ” 。

並且它需要刪除此網址,並從選定的下拉列表中替換為該網址,或者僅在“ http://example.com/theme ”之后替換此部分,例如,如果我選擇“藍色主題” ...它將替換“過去的” /themered.css”和“ themeblue / themeblue.css”

謝謝

為您的<link><select>添加一個id

<link id="themesheet" rel="stylesheet" href="http://example.com/theme/themered/themered.css">

<select id="theme">
  <option value="blue">Theme Blue</option>
  <option value="green">Theme Green</option>
  <option value="orange">Theme Orange</option>
</select>

現在使用這個:

document.getElementById('theme').addEventListener("change", function (e) {
  var theme = e.target.value;
  var URL = `//example.com/theme/theme${theme}/theme${theme}.css`;
  document.getElementById('themesheet').href = URL;
});

我還盡可能地縮短了所涉及的代碼。 只要您所有的主題都遵循該命名模式,它就可以正常工作。

即使您能夠在選擇選項上切換樣式表,也必須重新加載頁面才能使更改顯示在窗口中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM