2015-10-05 64 views
0

我已經提問相關問題here
現在試圖在同一個div <div class='this-div-only'></div>取代許多(不止一個)純文本一樣[make-this-class]上課像<div class='make-this-class'></div>[make-this-class2]一類像<div class='make-this-class2'></div>

問題是js只替換一個單獨的文本,意思是它不能替換其他文本的同一個div,當試圖替換文本多於一個時,它只替換同一個div的一個文本。下面給出的示例HTML和JS。將所有純文本替換爲相同的分類

HTML:

<div class='not-others-div'> 
text text [make-this-class] text 
</div> 

Text text text 

<div class='this-div-only'> <!-- this div only --> 
text [make-this-class] text [make-this-class2] and [make-this-class3] and 10 text like this <!--trying to replace text more then one--> 
</div> 

JQuery的:

$(".this-div-only").html(function(i, html) { 
    return html.replace(/\[(.*)\]/, $("<div />", {"class":"$1"})[0].outerHTML) 
}) 

那麼如何取代許多文字一類的jQuery DOM元素相同的div(10 十行文) ?

回答

1

添加g全局標誌的正則表達式,也需要使用.*?匹配最短

$(".this-div-only").html(function(i, html) { 
 
    return html.replace(/\[(.*?)\]/g, $("<div />", { 
 
    "class": "$1" 
 
    })[0].outerHTML) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class='this-div-only'> 
 
    <div class='this-div-only'> 
 
    <!-- this div only --> 
 
    text [make-this-class] text [make-this-class2] and [make-this-class3] and 10 text like this 
 
    <!--trying to replace text more then one--> 
 
    text [make-this-class] text [make-this-class2] and [make-this-class3] and 10 text 
 
    </div>

+0

嗨,謝謝,但是隻能替換兩個,不能替代其他8個文本(意思是我試圖用相同的潛水替換10個文本),請修復它。 – Aariba

+0

@Aabira:你可以添加一個http://jsfiddle.net –

+0

我已經試過它JSFiddle,但問題是它不給我像普通的HTML網頁相同的結果,意味着它在HTML網頁上獲得不同的結果。 – Aariba

1

嘗試增加g(全局),改變所有ocurrences:

$(".this-div-only").html(function(i, html) { 
    return html.replace(/\[(.*)\]/g, $("<div />", {"class":"$1"})[0].outerHTML) 
}) 

Pranav C Balan贏了我20秒

+0

嗨,謝謝,但是隻替換兩個,不能替換其他8個文本(意思是我試圖用相同的潛水替換10個文本),請修復它。 – Aariba