簡體   English   中英

如何更換不止一次?

[英]How to replace more than once?

到目前為止這是我的代碼:

$("h1.intro:contains('|')").each(function() {
    $(this).html($(this).html().replace('|','</span><br /><span>')) 
});

這只能工作一次,但它必須適用於所有這些“|”......

有任何想法嗎?

添加/g修飾符:

$("h1.intro:contains('|')").each(function() {
    $(this).html($(this).html().replace(/\|/g, '</span><br /><span>'));
});

更多信息:

g修飾符用於執行全局匹配(查找所有匹配項,而不是在第一次匹配后停止)。

如果您使用的是jQuery 1.4,則可以使用.html(function))簽名更好地完成此操作:

$("h1.intro:contains('|')").each(function() {
    $(this).html(function(idx, oldContent) {
        return oldContent.replace(/\|/g, '</span><br /><span>');
    });
});

這意味着您不必創建第二個jQuery實例,並且應該執行得更好。

您可以通過在“|”之后添加“/ g”為正則表達式添加修飾符

$("h1.intro:contains('|')").each(function() {
    $(this).html($(this).html().replace("|/g",'</span><br /><span>')) 
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM