使用javascript / jQuery向元素添加标题的最有效方法

时间:2013-02-15 10:21:29

标签: javascript jquery title object-literal

我在页面上有一些法语数字,最多24个作为段落元素中的文本(有些出现不止一次),我想通过它们并添加相关的英文翻译作为标题属性。我有一个解决方案,但我认为它不是最有效的,所以我只是想寻找一些帮助来写一些更整洁的东西,如果可能的话,并且对你的解决方案感兴趣。

由于

3 个答案:

答案 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部分相同