我将尝试使用jQuery添加一个类。
var tit = ('.tit a');
txt_animal = ['pig','horse','rabbit','cat','monkey'];
txt_fruit = ['melon','apple','kiwi','orange'];
txt_hobby = ['movie','ski','swim','dance','internet','baseball'];
$(txt_animal).each(function(i,v){
$(tit + ':contains("'+ v +'")').addClass('tag tag_animal');
}
$(txt_fruit).each(function(i,v){
$(tit + ':contains("'+ v +'")').addClass('tag tag_fruit');
}
$(txt_hobby).each(function(i,v){
$(tit + ':contains("'+ v +'")').addClass('tag tag_hobby');
}
工作正常。但我认为比这更好的方式。
如何优化javascript以获得最佳性能?
答案 0 :(得分:1)
为DRY优化。
var tit = ('.tit a');
var txt = {
"animal": ['pig','horse','rabbit','cat','monkey'],
"fruit": ['melon','apple','kiwi','orange'],
"hobby": ['movie','ski','swim','dance','internet','baseball']
};
for (var cat in txt) {
$(txt[cat]).each(function(i,v){
$(tit + ':contains("'+ v +'")').addClass('tag tag_' + cat);
});
}
答案 1 :(得分:1)
下面的代码应该避免重复(和昂贵的)DOM查询和通过可能的匹配重复迭代,通过对每个标记类使用正则表达式。
var txt = {
animal: /(pig|horse|rabbit|cat|monkey)/i,
fruit: /(melon|apple|kiwi|orange)/i,
hobby: /(movie|ski|swim|dance|internet|baseball)/i
};
$('.tit a').each(function() {
var $this = $(this); // saves three calls to `$(this)`
var t = $this.text(); // get the text contents of the link
for (var tag in txt) { // for each key word
if (txt[tag].test(t)) { // test the text against the regexp
$this.addClass('tag').addClass('tag_' + tag);
}
}
});