-1

我将尝试使用 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 以获得最佳性能?

4

2 回答 2

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);
  });
}
于 2012-05-13T14:33:06.377 回答
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);
       }
    }
});

http://jsfiddle.net/alnitak/DFcFH/1/

于 2012-05-13T14:55:21.800 回答