2011-08-17 32 views
0

我有一堆需要更換HREF鏈接:使用jQuery替換HREF,正則表達式

<a id="link" href="http://localhost:8091/tabid/99/catid/8/page1.aspx">Page1</a> 
<a id="link" href="http://localhost:8091/tabid/98/catid/8/page1.aspx">Page1</a> 
<a id="link" href="http://localhost:8091/tabid/97/catid/8/page1.aspx">Page1</a> 

的HREF應改爲: 的「http://本地主機:8091/tabid/1個 /catid/8/page1.aspx」

通過搜索,我發現:

$(document).ready(function() { 
    $("#link").each(function() { 
     this.href = this.href.replace("99", "1"); 
    }); 
}); 

這應該做的工作。但是,它只取代其中一個鏈接。任何人都可以幫助我在這裏的正則表達式?我需要將tabid/**/catid中的所有數字更改爲「」。

+0

你有多個元素具有相同的ID ...這是無效的。改變你的ID到類 –

回答

0

首先,將id更改爲class。其次,使這一變化:

this.href = this.href.replace(/tabid\/\d+/i, '/tabid/1'); 

現在只有tabid後取代了號碼,不是任何數量的字符串中的任何地方。

+0

感謝您的正則表達式,它的工作原理! – user899340

+0

然後通過一切手段+1回答,以便未來的觀衆可以知道。我得到了+15的破解。 –

0

id在文檔中是唯一的,您應該使用class來代替。

1

您的問題是使用id訪問多個元素:一個idaccording to the specification必須文檔中是唯一的。使用id會導致JavaScript返回它找到的第一個元素,而不是繼續搜索文檔(因爲必須只有一個)。

<a class="link" href="http://localhost:8091/tabid/**99**/catid/8/page1.aspx">Page1</a> 
<a class="link" href="http://localhost:8091/tabid/**98**/catid/8/page1.aspx">Page1</a> 
<a class="link" href="http://localhost:8091/tabid/**97**/catid/8/page1.aspx">Page1</a> 

隨着修正的jQuery:

$(document).ready(function() { 
    $(".link").each(function() { 
     this.href = this.href.replace("99", "1"); 
    }); 
}); 
1

id屬性指定用於HTML元素的唯一id

要多個元件使用class代替使用相同的名稱。在你的情況下,它們不是唯一的。嘗試使用CSS選擇器或定位所有「a」元素。