2013-02-08 74 views
0

我有,有時有多個br標籤在最後像下面驗證摘要:如何在HTML中使用JavaScript和jQuery替換「<br /><br />」與「<br />」?

<div id="ValidationSummary1" class="alert alert-error"> 
    Last 4-digits of Social Security number does not match 
    the Member record on file for the Member ID number you 
    have entered.<br /> 
    Date of Birth does not match the Member record on file for the Member ID 
    number you have entered.<br /><br /> 
</div> 

我試圖找到任何時候有兩個br標籤背靠背和一個像下面替換它:

$('#ValidationSummary1').replace('<br /><br />', '<br />'); 

我明白沒有replace()函數。像這樣簡單的東西會有什麼替代?

+0

可能重複:http://stackoverflow.com/questions/2145988/string-replace-in-jquery – David 2013-02-08 15:30:21

+0

試試這個:'$( '#ValidationSummary1')取代( '

','
');' – Asdfg 2013-02-08 15:39:55

+0

@Asdfg - jQuery本身沒有.replace()函數,這就是我發佈該問題的原因。 – 2013-02-08 15:41:44

回答

14

使用.html()來獲取和設置通過標準JS replace()的內容。

var div = $('#ValidationSummary1'); 
div.html(div.html().replace('<br /><br />', '<br />')); 
0

的JavaScript本身replace功能,並考慮到jQuery是內置的JavaScript框架,你必須使用該方法。所以,這意味着你將不得不做一個get-manipulate-set過程,而不是一些好的jQuery方法鏈接來完成它。

0
var $val= $('#ValidationSummary1'); 
$val.html($val.html().replace(/[<br>]+$/, '<br/>'); 

任何他們將通過一個
(更好的HTML)

0

被替換的
數量在你的情況(需要刪除HTML標籤)最好的解決方案是使用.text()代替.html() 。區別在於.html()保留了html標記,而.text()只保留了文本(刪除了任何html)。

例如:

var value1 = $('.some_div').html(); //returns text content with HTML tags 
var value2 = $('.some_div').text(); //returns only text content