我在页面上有一些法语数字,最多24个作为段落元素中的文本(有些出现不止一次),我想通过它们并添加相关的英文翻译作为标题属性。我有一个解决方案,但我认为它不是最有效的,所以我只是想寻找一些帮助来写一些更整洁的东西,如果可能的话,并且对你的解决方案感兴趣。
由于
答案 0 :(得分:4)
创建一个翻译对象,其中key
是法语编号,value
是英文翻译。
var translations = {
"un" : "one",
"deux" : "two",
...
};
$('.demonstration [class*="col"] p').each(function () {
var $this = $(this);
$this.attr('title', translations[$this.text().replace(/\s+/g, '')]);
});
答案 1 :(得分:1)
改为使用数组和对象:
var myTitles = { vingtquatre : 'twenty four', vingtdeux: 'twenty two' }; // add your other keys and values here in that same format, no matter what the order is inside.
$(this).attr('title', myTitles[$(this).text().replace(/\s+/g, '')]);
答案 2 :(得分:0)
您可以定义一个列表:
var nums = { 'un': 'one', 'deux': 'two', ... }
然后,将switch
替换为:
$(this).attr('title', nums[$(this).text().replace(/\s+/g, '')] || null);
请注意,|| null
适用于数字不在列表中的情况,即其行为与default
switch
部分相同