簡體   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