2012-11-01 37 views
0

我正在使用此方法查找並替換一段文本,但不確定它爲什麼不起作用?當我使用console.log時,我可以看到我想要替換的正確內容,但最終結果不起作用:jQuery替換文本不起作用

(function($) { 
    $(document).ready(function() { 
     var theContent = $(".transaction-results p").last(); 
     console.log(theContent.html()); 
     theContent.html().replace(/Total:/, 'Total without shipping:'); 
    }); 
})(jQuery); 

有什麼想法?

謝謝!

+0

與string.replace返回一個字符串 - 它不會做的替換字符串引用...'theContent.html(theContent.html()。replace(/ Total:/,'Total shipping:'));' – Archer

+0

@diEcho這不是PHP,你不包裝正則表達式引號。 – Barmar

回答

0

你有多餘的:字符串搜索還可以指派回theContent的HTML

Live Demo

$(document).ready(function() { 
     var theContent = $(".transaction-results p").last(); 
     console.log(theContent.html()); 
     theContent.html(theContent.html().replace(/Total/, 'Total without shipping:')); 
    }); 
3

字符串被替換,但您沒有將字符串重新分配給元素的html。使用return

theContent.html(function(i,h){ 
    return h.replace(/Total:/, 'Total without shipping:'); 
}); 

JS Fiddle demo(慷慨解囊由diEcho)。

參考文獻:

+0

工作演示添加 – diEcho

+1

謝謝親切! –

0
(function($) { 
    $(document).ready(function() { 
     var theContent = $(".transaction-results p").last(); 
     console.log(theContent.html()); 
     theContent.html(theContent.html().replace('Total:', 'Total without shipping:')); 
    }); 
})(jQuery); 

你爲什麼/Total:/,而不是'Total'像一個正常的字符串?

- 來自@David Thomas的解決方案工作。

+0

因爲他使用的是正則表達式,而不是字符串。 –