how to improve jquery's performance or use regular replace?
I'd like 开发者_如何学Goto add prefix id to all DOM element's several attributes.
what is the best way ?
I found jquery's find and each function is slow. should I use regular replace ?
jquery's code for example:
$("body").find("id").each(function(){
$(this).attr("id", "AAA_" + $(this).attr("id"));
});
$("body").find("label[for]").each(function(){
$(this).attr("for", "AAA_" + $(this).attr("for"));
});
First, you're looking for id
elements, not elements with an id
attribute. Use [id]
instead.
Second, use the callback argument to attr
:
$('[id]').attr('id', function(idx, oldId) {
return 'AAA_' + oldId;
});
$('label[for]').attr('for', function(idx, oldFor) {
return 'AAA_' + oldFor;
});
Do you really want to modify HTML attribute values, or do you want to modify DOM properties? I suspect that you actually want to deal with DOM properties.
The following will add a prefix to nominated DOM properties if that property has a value other than empty string. Be careful, some properties are boolean, adding a string prefix may have unusual results.
I'd be interested to know how much faster this is than jQuery.
function prefixProperty(prop, prefix) {
var el, els = document.getElementsByTagName('*');
var i = els.length;
while (i--) {
el = els[i];
// Only modify property if it has a value other than empty string
if (el[prop].length) {
el[prop] = prefix + el[prop];
}
}
}
I would change your selector to (i assume only imputs) and do it all in one loop
$('input').each(function(){
var cur_id = this.id;
$('label[for:="'+cur_id +'"]').attr('for',"AAA_" + cur_id );
cur_id = "AAA_" + cur_id ;
});
精彩评论