简体   繁体   中英

Javascript caching tools and techniques

I have a requirement where in I want to loop through all the DropDown (select) controls on a page. I am picking all the DropDown controls using:

var DropDowns = document.getElementByTagName('select');

I loop through these DropDowns to set an option programatically of few controls:

for (i=0; i<= DropDowns.Length; i++)
{
    var CurrentControl = DropDowns[i];
    CurrentControl.options[CurrentControl.selectedIndex].value = 1;
}

Is there any Javascript framework which supports caching? I want to cache all the DropDown control names and loop through the cached names instead of directly looping through Document object.

Are there any tricks to increase the performance of the loop?

I don't think that you're going to see huge improvements in performance for a loop that is only iterating through 30-40 elements, but some browsers will get a huge speed boost from looping through an array instead of a NodeList or HTMLCollection as it is called in some browsers that implement DOM level 1.

So, to answer your question, you can "cache" the objects etc. in an array and it should speed up that loop for future iterations.

Be aware that you need to keep this array up-to-date because it is not "live" like the DOM is.

In jquery, it would look something like this:

var $menus = $('select');
$.each($menus, function(index, menu) {
    // Do whatever you want to the menu here
};

我建议采用另一种方法-将选项保存在具有逗号分隔值的隐藏字段中,并在页面加载时通过解析分隔值来设置控件的值。

I think you're already doing this much more efficiently than some of the answers describe. Bear in mind you're not continuously looping through the document, you're looping through your cached NodeList of DropDowns . If you want to change each one of these elements, then you will inevitably need to loop through them to change them individually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM