2012-02-10 60 views
-3

我有以下的HTML代碼jQuery的查找替換

<a href="javascript:void(0);" onClick="javascript:OpenNewWindow('/help_email.asp?ProductCode=122030', 350, 250);" class="pricecolor colors_productprice"><b><span class="PageText_L657n"><br><input type="Button" font face="arial" size="2" color="#ffbb00" value="submit best offer"> </Button> 

我想要做的就是找到help_email.asp的所有出現,並與help_email.php更換。

+0

http://stackoverflow.com/questions/2145988/jquery-string-replace – Igor 2012-02-10 15:18:38

+1

help_email.asp沒有出現在您發佈的代碼中的任何地方? – 2012-02-10 15:19:36

+0

剛剛更新了代碼 – user580950 2012-02-10 15:56:41

回答

3

使用

$('body').html($('body').html().replace('help_email.asp','help_email.php')); 
+0

這種方式如果在代碼運行之前,頁面上存在與元素相關的任何事件,或者使用'prop()'而不是'attr()')添加的屬性(不屬性,因爲他們沒有寫在HTML本身 – Meligy 2012-02-10 15:28:33

+0

是的,這個問題不是特定的,只是想在字符串不是錨點或鏈接的情況下提供替代。 – isJustMe 2012-02-10 15:36:40

3

嘗試

$(function() { 
    var anchors = $("a[href*='help_email.asp'], a[onclick*='help_email.asp']"); 

    anchors.each(function() { 
     var anchor = $(this); 

     var originalHref = anchor.attr("href"); 
     anchor.attr("href", originalHref.replace(".asp", ".php")); 

     var originalClick = anchor.attr("onclick"); 
     anchor.attr("onclick", originalClick.replace(".asp", ".php")); 
    }); 
}); 

注意replace是一個標準的JS函數,而不是jQuery的具體。

參考文獻:

0

假設 'help_email.asp' 只出現在錨標籤的屬性href ...

$('a').each(function() { 
    var href = $(this).attr('href'); 
    href = href.replace('help_email.asp', 'help_email.php'); 
    $(this).attr('href', href); 
}) 

但是,爲什麼不只是做這個服務器端,所以正確的URL已經嵌入在頁面中?