繁体   English   中英

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

[英]Most efficient way to add titles to elements with javascript/jQuery

我在页面上的段落元素中有一些法语数字(最多24个)作为文本(有些出现多次),我想遍历这些数字并将相关的英语翻译添加为title属性。 我有一个解决方案,但我认为这不是最有效的,因此,我正在寻找一些帮助,以便在可能的情况下编写更整洁的东西,并对您的解决方案感兴趣。

谢谢

创建一个翻译对象,其中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, '')]);
});

改用数组和对象:

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, '')]);

您可以定义一个列表:

var nums = { 'un': 'one', 'deux': 'two', ... }

然后,将switch替换为:

$(this).attr('title', nums[$(this).text().replace(/\s+/g, '')] || null);

请注意|| null || null是用于当号码不在列表中时,即它的作用类似于switchdefault部分

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM