jQuery查找并替换多个项目 [英] jquery find and replace multiple items

查看:133
本文介绍了jQuery查找并替换多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a monthly table that needs to be translated for each languages

这样的事情(显然行不通)

Something like this (doesnt work obviously)

$('.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'));

});

推荐答案

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

You can maintain a mapping between the original and replacement strings, and pass a function to text():

var mapping = {
    "Tam": "Jan",
    "Hel": "Feb",
    // ...and so on...
};

$("#monthly th").text(function(index, originalText) {
    return mapping[originalText];
});

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

If you want to replace only part of the text, you can use nested arrays rather than an object:

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]);
});

这篇关于jQuery查找并替换多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆