jQuery Optimize link "href" selection
I'm changing the class of 开发者_运维百科"a" tag according to "href" file type. It works fine. Here's the code:
$('#divComment a[href$=".pdf"]').removeClass().addClass("pdf");
$('#divComment a[href$=".doc"]').removeClass().addClass("word");
$('#divComment a[href$=".docx"]').removeClass().addClass("word");
$('#divComment a[href$=".zip"]').removeClass().addClass("zip");
$('#divComment a[href$=".jpg"]').removeClass().addClass("image");
$('#divComment a[href$=".xls"]').removeClass().addClass("excel");
$('#divComment a[href$=".xlsx"]').removeClass().addClass("excel");
How do I optimize this code?
If by optimization, you mean to make the code more concise and maintainable, then you could create a look-up table.
Example:
var extensions = {
'.pdf': 'pdf',
'.doc': 'word'
// ...
};
$('#divComment a').each(function() {
var match = this.href.match(/\..+$/);
if(match && extensions[match[0]]) {
$(this).removeClass().addClass(extensions[match[0]]);
}
});
try this
$(document).ready(function(){
var extensions = {
'pdf': 'pdf',
'doc': 'word'
};
$('#divComment a').each(function() {
var href = this.href;
var ext = href.split('.').pop().toLowerCase();
if(extensions[ext]) {
$(this).addClass(extensions[ext]);
}
});
});
idea from @Felix Kling post..
jsfiddle
Try a switch case on the $('#divComment a').attr('href').
精彩评论