2012-11-01 38 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

因为他使用的是正则表达式,而不是字符串。 –