質問

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 am suggesting a different approach - Save the options in a hidden field with a comma separated values and on page load set the values of control by parsing the , separated values.

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top