admin管理员组文章数量:1391934
this following piece of code works, but it sort of makes the browser quirk just a bit. Nothing major. I'm wondering if there would be a way to make this more efficient? Can I use caching or somehow populate one select and then just copy it to the other 5. (there are 6 drop downs with a class of 'mask' on the page.)
Any help would be greatly appreciated!
$('.mask').each(function () {
$(this).append($('<option/>').val("").text(""));
for (var i = 1; i < 256; i++) {
$(this).append($('<option/>').val(i).text(i));
}
});
});
this following piece of code works, but it sort of makes the browser quirk just a bit. Nothing major. I'm wondering if there would be a way to make this more efficient? Can I use caching or somehow populate one select and then just copy it to the other 5. (there are 6 drop downs with a class of 'mask' on the page.)
Any help would be greatly appreciated!
$('.mask').each(function () {
$(this).append($('<option/>').val("").text(""));
for (var i = 1; i < 256; i++) {
$(this).append($('<option/>').val(i).text(i));
}
});
});
Share
Improve this question
asked Dec 22, 2010 at 21:27
user342706user342706
2 Answers
Reset to default 11You can create the nodes once then clone them, like this:
var temp = $('<select/>');
$('<option/>').val("").text("").appendTo(temp);
for (var i = 1; i < 256; i++) {
$('<option/>').val(i).text(i).appendTo(temp);
}
temp.children().clone().appendTo('.mask');
Instead of doing a lot of individual appends to the DOM (which is very costly) this batches all the elements up in a document fragment then clones them, appending in batches (one batch per select).
It's much faster (around 3-10 times, as tested here) to build up the HTML yourself in a single string:
var html = "<option value=''></option>";
for (var i = 1; i < 256; i++) {
html += "<option value='" + i + "'>" + i + "</option>";
}
$(".mask").append(html);
See performance test paring the current options in this thread: http://jsperf./appending-options-jquery
本文标签: javascriptmore efficient jqueryStack Overflow
版权声明:本文标题:javascript - more efficient jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744742787a2622709.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论