jquery查找并替换多个项目

我有一个月表,需要为每种语言翻译

像这样的东西(显然不起作用)

$('.lang-en #monthly th').each(function() { var text = $(this).text(); $(this).text(text.replace('Tam', 'Jan')); $(this).text(text.replace('Hel', 'Feb')); $(this).text(text.replace('Maa', 'Mar')); $(this).text(text.replace('Huh', 'Apr')); $(this).text(text.replace('Tou', 'May')); $(this).text(text.replace('Kes', 'Jun')); $(this).text(text.replace('Hei', 'Jul')); $(this).text(text.replace('Elo', 'Aug')); $(this).text(text.replace('Syy', 'Sep')); $(this).text(text.replace('Lok', 'Oct')); $(this).text(text.replace('Mar', 'Nov')); $(this).text(text.replace('Jou', 'Dec')); $(this).text(text.replace('Yht', 'Total')); }); 

您可以维护原始字符串和替换字符串之间的映射,并将函数传递给text() :

 var mapping = { "Tam": "Jan", "Hel": "Feb", // ...and so on... }; $("#monthly th").text(function(index, originalText) { return mapping[originalText]; }); 

编辑:如果您只想替换部分文本,您可以使用嵌套数组而不是对象:

 var mapping = [ ["Tam", "Jan"], ["Hel", "Feb"], // ...and so on... ]; $("#monthly th").text(function(index, originalText) { var pattern = mapping[index]; return originalText.replace(pattern[0], pattern[1]); });