简体   繁体   English

Javascript缓存工具和技术

[英]Javascript caching tools and techniques

I have a requirement where in I want to loop through all the DropDown (select) controls on a page. 我有一个要遍历页面上所有DropDown(选择)控件的位置。 I am picking all the DropDown controls using: 我使用以下方法来选择所有DropDown控件:

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

I loop through these DropDowns to set an option programatically of few controls: 我遍历这些DropDown,以编程方式设置几个控件的选项:

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? 是否有任何支持缓存的Javascript框架? I want to cache all the DropDown control names and loop through the cached names instead of directly looping through Document object. 我想缓存所有DropDown控件名称,并通过缓存的名称循环,而不是直接通过Document对象循环。

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. 我认为您不会看到仅循环访问30至40个元素的循环在性能方面的巨大改进,但是某些浏览器将通过遍历数组而不是NodeListHTMLCollection来获得巨大的速度提升。在实现DOM级别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. 请注意,您需要保持此数组为最新,因为它不像DOM那样“活跃”。

In jquery, it would look something like this: 在jquery中,它看起来像这样:

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 . 请记住,你不是不断通过循环文件,你通过你的缓存循环NodeListDropDowns If you want to change each one of these elements, then you will inevitably need to loop through them to change them individually. 如果要更改这些元素中的每个元素,那么不可避免地需要遍历它们以分别更改它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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