使用JavaScript的HTML DOM选择对象
如何使用javascript在选择选项中添加多个值,我下面的脚本仅在触发时显示空的选择选项使用JavaScript的HTML DOM选择对象,javascript,jquery,html,Javascript,Jquery,Html,如何使用javascript在选择选项中添加多个值,我下面的脚本仅在触发时显示空的选择选项 var tr = document.createElement("TR"); var td=document.createElement("TD"); txt=document.createElement('SELECT'); txt.style.width = '285px'; txt.maxLength = 50; txt.se
var tr = document.createElement("TR");
var td=document.createElement("TD");
txt=document.createElement('SELECT');
txt.style.width = '285px';
txt.maxLength = 50;
txt.setAttribute("type","text");
txt.setAttribute("option","value","10001"),("text","Larry");
txt.setAttribute("option","value","10002"),("text","Nancy");
txt.setAttribute("class","form-control");
txt.setAttribute("name","StoreCodeLine" + line);
txt.setAttribute("id","StoreCodeLine" + line);
td.setAttribute("align","center");
td.appendChild(txt);
tr.appendChild(td);
document.getElementById("tblGroup").appendChild(tr);
选项
不是一个属性,它是select
的子元素
此外,如果没有text
属性,则需要更改其innerHTML
:
var行=1;
var tr=document.createElement(“tr”);
var td=document.createElement(“td”);
txt=document.createElement('SELECT');
txt.style.width='285px';
txt.maxLength=50;
setAttribute(“类型”、“文本”);
setAttribute(“类”、“窗体控件”);
setAttribute(“名称”、“存储代码行”+行);
setAttribute(“id”,“StoreCodeLine”+行);
td.setAttribute(“对齐”、“居中”);
var opt1=document.createElement(“选项”);
opt1.setAttribute(“值”,“10001”);
opt1.innerHTML=“Larry”;
var opt2=document.createElement(“选项”);
opt2.setAttribute(“值”,“10002”)
opt2.innerHTML=“Nancy”;
txt.appendChild(opt1);
txt.appendChild(opt2);
td.appendChild(txt);
tr.appendChild(td);
document.getElementById(“tblGroup”).appendChild(tr)代码>
您可能需要为此使用一个循环
var tr = document.createElement("TR");
var td=document.createElement("TD");
txt=document.createElement('SELECT');
txt.style.width = '285px';
txt.maxLength = 50;
var option = document.createElement("option");
option.text = "Larry";
option.value = "10001";
txt.add(option);
var option = document.createElement("option");
option.text = "Nancy";
option.value = "10002";
txt.add(option);
txt.setAttribute("class","form-control");
td.setAttribute("align","center");
td.appendChild(txt);
tr.appendChild(td);
document.getElementById("tblGroup").appendChild(tr);
与前面提到的其他元素一样,选项
不是它自己的属性,它是选择
的子元素。您可以像下面这样直接附加选项。第一个参数是text
,第二个参数是value
txt.add(new Option("Larry","10001"));
txt.add(new Option("Nancy","10002"));
var tr=document.createElement(“tr”);
var td=document.createElement(“td”);
txt=document.createElement('SELECT');
txt.style.width='285px';
txt.maxLength=50;
setAttribute(“类型”、“文本”);
添加(新选项(“拉里”、“10001”);
添加(新选项(“Nancy”、“10002”);
setAttribute(“类”、“窗体控件”);
td.setAttribute(“对齐”、“居中”);
td.appendChild(txt);
tr.appendChild(td);
document.getElementById(“tblGroup”).appendChild(tr)代码>
你能给我们一个HTML或者创建一个代码片段让我们试试吗?我不知道你从哪里得到的txt.setAttribute(“option”,…)
可能是重复的,但它看起来很无意义。。。选项是独立的HTML元素,驻留在select中,它们不是它的属性。感谢您理解我的问题,它对我有用谢谢!谢谢你不回答我的问题,我添加了txt.add(选项);在你的剧本上谢谢!