最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - more efficient jquery - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 11

You 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

发布评论

评论列表(0)

  1. 暂无评论