Javascript 如何以编程方式添加下拉列表(<;select>;)?
我想创建一个函数,以编程方式在页面上添加一些元素 假设我想添加一个包含四个选项的下拉列表:Javascript 如何以编程方式添加下拉列表(<;select>;)?,javascript,html,drop-down-menu,html-select,Javascript,Html,Drop Down Menu,Html Select,我想创建一个函数,以编程方式在页面上添加一些元素 假设我想添加一个包含四个选项的下拉列表: <select name="drop1" id="Select1"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
沃尔沃汽车
萨博
梅赛德斯
奥迪
我该怎么做呢?这将起作用(纯JS,附加到id的divmyDiv
):
演示:
var myParent=document.body;
//创建要添加的选项数组
var数组=[“沃尔沃”、“萨博”、“梅卡德斯”、“奥迪”];
//创建并附加选择列表
var selectList=document.createElement(“选择”);
selectList.id=“mySelect”;
myParent.appendChild(选择列表);
//创建并附加选项
对于(var i=0;ivar sel=document.createElement('select');
sel.name='drop1';
sel.id='Select1';
var cars=[
“沃尔沃”,
“萨博”,
“梅赛德斯”,
“奥迪”
];
var选项_str=“”;
汽车。forEach(功能(汽车){
选项_str+=''+汽车+'';
});
sel.innerHTML=options\u str;
window.onload=函数(){
文件.正文.附件(sel);
};
我很快就制作了一个可以实现这一点的函数,这可能不是最好的方法,但它很简单,应该是跨浏览器的,请也知道我不是JavaScript专家,所以任何提示都很好:)
纯Javascript创建元素解决方案
这是params
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
这个函数将适合如果你必须附加许多元素,如果有任何方法来改进这个答案,请让我知道
编辑:
这是一个工作演示
这可以高度定制,以适应您的项目 此代码将动态创建一个选择列表。首先,我创建一个包含汽车名称的数组。其次,我动态创建一个select元素,将其分配给变量“sEle”,并将其附加到html文档的主体中。然后我使用for循环遍历数组。第三,我动态创建option元素并将其分配给变量“oEle”。使用if语句,我将属性“disabled”和“selected”分配给第一个option元素[0],以便它始终处于选中状态并被禁用。然后,我创建一个文本节点数组“oTxt”,以附加数组名称,然后将文本节点附加到option元素,该元素随后附加到select元素
var数组=[“选择汽车”、“沃尔沃”、“萨博”、“梅尔韦德斯”、“奥迪”];
var sEle=document.createElement('select');
document.getElementsByTagName('body')[0].appendChild(sEle);
对于(变量i=0;i
const cars=[‘沃尔沃’、‘萨博’、‘梅尔韦德斯’、‘奥迪’];
让domSelect=document.createElement('select');
domSelect.multiple=true;
document.getElementsByTagName('body')[0].appendChild(domSelect);
用于(汽车中的常数i){
让optionSelect=document.createElement('option');
让optText=document.createTextNode(cars[i]);
选项select.appendChild(optText);
document.getElementsByTagName('select')[0].appendChild(optionSelect);
}
这很简单,但也很棘手,但以下是您想要的,希望对您有所帮助:
此函数生成1990年至2018年的选择列表
我认为这个例子可以帮助你,如果你想增加任何其他价值只是
更改x和y的值;)
函数下拉列表(){
var起点=1990年;
var今天=2019年;
文件。填写(“”);
对于(var i=start;i,这里是由提供的答案的ES6版本
const sel=document.createElement('select');
sel.name='drop1';
sel.id='Select1';
常数车=[
“沃尔沃”,
“萨博”,
“梅赛德斯”,
“奥迪”,
];
const options=cars.map(car=>{
const value=car.toLowerCase();
返回`${car}`;
});
sel.innerHTML=选项;
window.onload=()=>document.body.appendChild(sel);
这是一个ES6版本,转换为vanilla JS应该不会太难,但我已经有了jQuery:
功能选择(选项,已选择){
返回Object.entries(options).reduce((r[k,v])=>r.append($('').val(k).text(v)),$('').val(选中);
}
$('body').append(选择({'option1':'label 1','option2':'label 2'},'option2'));
查看文档。createElement
和元素。appendChild
@Koukoulofloos我的答案有用吗?@WooCaSh我问什么就做什么,但我更喜欢用简单的javascript编写。@Koukoulofloos原因?如果这是一个商业项目,强烈建议使用库。@JanDvorak不,我只是在做一些测试ting。这是一个奇迹!一个非jQuery解决方案。您可能只想设置属性,而不是使用setAttribute()
。这并不重要,而是使用新选项(文本、值)
是创建
elements@Ian--谢谢你的提示,仍然在学习纯JS,首先学习了jQuery不幸的是,试图用纯JS做任何事情都有点棘手:)@tymeJV当然,只是想帮助改进你的答案(尽管它很好)。这是非常正确的,尽管有时候如果你不使用jQuery:)就可以做这件事会让你感觉更有价值,供大家参考-。而且我发现没有必要使用setAttribute()
/getAttribute()
,除非你使用的是自定义属性(包括data-*
)属性。我知道在使用这些方法时也会有不一致的地方,所以我不知道你也可以使用selectList.add(option)
((向上滚动一点),)很久以前add()/remove()在不同的浏览器中工作方式不同,所以ppk建议不要给我们
function createElement(){
var element = document.createElement(arguments[0]),
text = arguments[1],
attr = arguments[2],
append = arguments[3],
appendTo = arguments[4];
for(var key = 0; key < Object.keys(attr).length ; key++){
var name = Object.keys(attr)[key],
value = attr[name],
tempAttr = document.createAttribute(name);
tempAttr.value = value;
element.setAttributeNode(tempAttr)
}
if(append){
for(var _key = 0; _key < append.length; _key++) {
element.appendChild(append[_key]);
}
}
if(text) element.appendChild(document.createTextNode(text));
if(appendTo){
var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
target.appendChild(element)
}
return element;
}
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
var options = [
createElement('option', 'Volvo', {value: 'volvo'}),
createElement('option', 'Saab', {value: 'saab'}),
createElement('option', 'Mercedes', {value: 'mercedes'}),
createElement('option', 'Audi', {value: 'audi'})
];
createElement('select', null, // 'select' = name of element to create, null = no text to insert
{id: 'Select1', name: 'drop1'}, // Attributes to attach
[options[0], options[1], options[2], options[3]], // append all 4 elements
'body' // append final element to body - this also takes a element by id without the #
);
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
function dropDown(){
var start = 1990;
var today = 2019;
document.write("<select>");
for (var i = start ; i <= today; i++)
document.write("<option>" + i + "</option>");
}
document.write("</select>");
dropDown();
const countryResolver = (data = [{}]) => {
const countrySelecter = document.createElement('select');
countrySelecter.className = `custom-select`;
countrySelecter.id = `countrySelect`;
countrySelecter.setAttribute("aria-label", "Example select with button addon");
let opt = document.createElement("option");
opt.text = "Select language";
opt.disabled = true;
countrySelecter.add(opt, null);
let i = 0;
for (let item of data) {
let opt = document.createElement("option");
opt.value = item.Id;
opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
countrySelecter.add(opt, null);
}
return countrySelecter;
};