1

我有一张需要为每种语言翻译的月表

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

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

});
4

1 回答 1

2

您可以维护原始字符串和替换字符串之间的映射,并将函数传递给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]);
});
于 2012-06-08T10:24:32.333 回答