2012-04-17 88 views
0

我允許我的用戶在我的網站上發佈消息。我希望能夠更換的東西,如一個鏈接彈出%將被格式化爲:用鏈接替換字符串的正確方法

<a href="ss/pop.wav">%pop</a>

%的爆炸將變爲:

<a href="ss/explosion.wav">%explosion</a>

我使用jQuery ,有誰知道我會怎麼做?

回答

2

此代碼doen't需要的jQuery:

"The %pop is here".replace(/%(\w+)/g, '<a href="ss/$1.wav">%$1</a>') 

結果:

「的< A HREF =」 SS /彈出。 WAV「>%彈出</A >在這裏」

+0

哇,工作完美。謝謝! – FreeSnow 2012-04-18 00:33:23

1
$("a").each(function() { 
    var href = $(this).val().split("%")[1]; 
    if(href.length > 0) { 
     $(this).attr("href", "ss/"+href+".wav"); 
    } 
});​ 

你要定製選擇,以配合您的HTML架構,當然,通過頁面上的所有元素a迭代可能是麻煩和/或緩慢。 (我建議使用一類,爲簡潔起見)

1

指定一個類或相對的標籤,遍歷所有實例來獲取值的括號內,過濾%和分配中的href。

$('a.get-path').each(function(){ 

    // Cache the $(this) object 
    var $this = $(this); 

    // Strip out the % from the "file name" and create the path 
    var myPath = $this.html().replace(/%(.*)/, "ss/$1.wav"); 

    $this.attr('href', myPath); 

}); 
2

使用jQuery的組合和正則表達式:

jQuery("div.message").each(function() { 
    jQuery(this).html(jQuery(this).text().replace(
     /%(\w+)/g,"<a href='ss/$1.wav'>%$1</a>" 
    )); 
}); 

根據需要更改 「div.message」 選擇。 迭代每個div.message,並根據需要替換%foo的每個出現次數。

+0

這一次幫助我取代了每場比賽。感謝evophage。 – Hugo 2013-12-07 06:59:04

相關問題