質問

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. 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.

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:

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

note that || null is for when the number isn't the list i.e. it acts like the default part of the switch

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top