admin管理员组文章数量:1404923
My function clears out a dropdownlist and then re-populates it. Do I really need all this or is there a more concise way to do this? Meaning do I need to create a new document.createElement("option"); or is there a shortcut?
for (blah blah blah)
{
objNewOption = document.createElement("option");
objNewOption.value = day;
objNewOption.text = day;
birthDay.options.add(objNewOption);
}
My function clears out a dropdownlist and then re-populates it. Do I really need all this or is there a more concise way to do this? Meaning do I need to create a new document.createElement("option"); or is there a shortcut?
for (blah blah blah)
{
objNewOption = document.createElement("option");
objNewOption.value = day;
objNewOption.text = day;
birthDay.options.add(objNewOption);
}
Share
Improve this question
asked Nov 6, 2009 at 19:17
PositiveGuyPositiveGuy
47.8k112 gold badges314 silver badges479 bronze badges
4 Answers
Reset to default 2var new_option_element = new Option(display_label, value, selected_boolean);
Create your own shortcut...
function x() { return document.createElement("option"); }
for(blah blah blah) {
objNewOption = x();
}
Is it really that long? That's not that much to type.
If you want to use a framework, like MooTools or Prototype, they have an Element class, letting you do it in one line.
var opt = new Element('option', { value: day, text: day });
The biggest problem with the document.createElement technique is that it's really SLOW. Using a framework is best, but either way, I'd suggest building the options list and setting the innerHTML property on the select box.
strOptions = "";
for (blah blah blah)
{
strOptions += '<option value="' + day + '">' + day + '</option>'
}
birthDay.innerHTML = strOptions;
The browser is going to be able to parse the HTML a lot faster than you'll be able to build these elements by hand.
In response to the ment, this is really why using a platform library is always worth it. In YUI3, I do this:
var fillSelectbox = function(select, optionList) {
var i, option = '';
for (i = 0; i < optionList.length; i += 1) {
option += '<option value="' + optionList[i].Value + '" selected="' + (optionList[i].selected ? '"selected"' : '""') + '">' + optionList[i].Text + '</option>';
}
select.append(option);
select.set('selectedIndex', -1);
};
Where select is the selectNode and optionList is a JavaScript array.
本文标签: javascriptShortcut for documentcreateElement(quotoptionquot)Stack Overflow
版权声明:本文标题:javascript - Shortcut for document.createElement("option")? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744879080a2630096.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论