簡體   English   中英

如何使用Javascript替換特定的href鏈接?

[英]How to replace a specific href link using Javascript?

我會再次嘗試這個,因為我不確定上次我提出一個非常明確的問題...我有一個頁面有很多鏈接的圖像。 我想使用javascript更改其中一個圖像鏈接(它是徽標)。 我無法直接編輯“body”html,但可以將js放在“head”區域。

這是html代碼:

<div id="ctl00">
  <h1 class="logo">
  <a href="http://www.store.domain.co.nz" title="Menswear"><img src="/user/files/logo.png title="Menswear" alt="Menswear"></a>
  </h1>
</div>

我想將html更改為:

<div id="ctl00">
    <h1 class="logo">
<a href="http://www.domain.co.nz" title="Menswear"><img src="/user/files/logo.png title="Menswear" alt="Menswear"></a>
</h1>
</div>

基本上我想從URL中刪除“。store”,但只刪除此實例,而不是頁面上的所有URL。

一種方法是使用href值來查找錨點

 var a = document.querySelector('a[href="http://www.this.link.co.nz"]'); if (a) { a.setAttribute('href', 'http://www.that.link.co.nz') } 
 <a href="http://www.this.link.co.nz" title="this link"> <img src="/filename.jpg" /> </a> 

檢查DOM功能:

 var x = document.getElementsByTagName("a") for (i=0;i<x.length;++i) { if (x[i].getAttribute("href") == "http://www.this.link.co.nz") { x[i].setAttribute("href", "http://www.that.link.co.nz") x[i].setAttribute("title", "that link") x[i].replaceChild( document.createTextNode( "changed img:filename.jpg" ), x[i].firstChild ) } } 
 <p><a href="http://www.this.link.co.nz" title="this link"> img:filename.jpg </a> </p> <p><a href="http://www.this.link.co.nz" title="this link"> img:filename.jpg </a> </p> 

設置x包含所有一個元素的數組。

暫無
暫無

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

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