jQuery change multiple attributes or replace entire html
I was wondering if it were more efficient/faster to change multiple attributes with jQuery or to just change replace all the html in one go. This is the code i am using at the moment.
// shows the table and changes the image to up
showTable = function(tableId){
$('#img' + tableId).attr("src", images["up"]).attr("alt", "Hide Table").attr("title", "Hide Table");
$('#' + tableId).fadeIn(250);
}
or would this be faster?
// shows the table and changes the im开发者_JAVA百科age to up
showTable = function(tableId){
$('#img' + tableId).replaceWith('some html');
$('#' + tableId).fadeIn(250);
}
$('#greatphoto').attr({
alt: 'Beijing Brush Seller',
title: 'photo by Kelly Clark'
});
Example taken from jQuery Documentation.
Given that you're taking a quarter of a second to fade in the result and this isn't a tight loop, you're not going to notice any performance difference between the two. As yan.kun points out, you can make the code a bit more concise by using the multi-set (map) version of attr
, but with three attributes not in a tight loop, it's not going to make a speed difference. (If it were, I'd avoid calling attr
entirely and use the element's own reflected properties — src
, alt
, and title
are all reflected.)
Having said that, there are other reasons to update elements rather than replace them. For instance, if you have any handlers attached to the elements, if you update the elements' attributes, the handlers remain attached; if you replace the elements, the handlers aren't attached (because they were attached to the old ones). Replacing elements also causes reflow, which can be significant (or not) depending on your DOM structure.
精彩评论