[英]Most efficient way to add titles to elements with javascript/jQuery
I have some French numbers up to 24 as text in paragraph elements (some occurring more than once) on a page and I want to go through them and add the relevant English translation as a title attribute. 我在页面上的段落元素中有一些法语数字(最多24个)作为文本(有些出现多次),我想遍历这些数字并将相关的英语翻译添加为title属性。 I've got a solution, but I don't think it's the most efficient, so I'm just looking for a bit of help to write something neater, if possible, and was interested in your solutions.
我有一个解决方案,但我认为这不是最有效的,因此,我正在寻找一些帮助,以便在可能的情况下编写更整洁的东西,并对您的解决方案感兴趣。
Thanks 谢谢
Create a translations object where the key
is the number in French and the value
is the English translation. 创建一个翻译对象,其中
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, '')]);
});
Use Arrays and Objects instead: 改用数组和对象:
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, '')]);
You can define a list: 您可以定义一个列表:
var nums = { 'un': 'one', 'deux': 'two', ... }
And then, replace switch
with this: 然后,将
switch
替换为:
$(this).attr('title', nums[$(this).text().replace(/\s+/g, '')] || null);
note that || null
请注意
|| null
|| null
is for when the number isn't the list ie it acts like the default
part of the switch
|| null
是用于当号码不在列表中时,即它的作用类似于switch
的default
部分
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.