Javascript 获取<;选择>;添加选项时更新的步骤
我有一个选择,看起来像这样Javascript 获取<;选择>;添加选项时更新的步骤,javascript,html,Javascript,Html,我有一个选择,看起来像这样 <select id="mySelect"><option value="">Please select</option></select> 问题是您必须单击“选择”按钮才能显示myText。如何使myText(带有myValue)在运行javascript时立即显示?使用body标记的onLoad属性加载脚本?e、 g <body onload="initSelect()"> 或者简单地将脚本放在s
<select id="mySelect"><option value="">Please select</option></select>
问题是您必须单击“选择”按钮才能显示myText。如何使myText(带有myValue)在运行javascript时立即显示?使用body标记的onLoad属性加载脚本?e、 g
<body onload="initSelect()">
或者简单地将脚本放在select标记之后:
<select>...</select>
<script>//code to generate the options</script>
。。。
//生成选项的代码
添加elSel.selectedIndex=0代码>到脚本的末尾。如果您将拥有多个项目,并且希望选择最后一个项目,请使用elSel.options.length-1
<html>
<head>
<script language="javascript">
function addItem() {
var elSel = document.getElementById('test');
elSel.options[0].value = '1';
elSel.options[0].text = 'new value';
elSel.selectedIndex = 0;
}
</script>
</head>
<body>
<form>
<select id="test"><option value="1">- SELECT AN ITEM -</option></select>
<input type="button" value="Add Item" onclick="addItem();" />
</form>
</body>
</html>
函数addItem(){
var elSel=document.getElementById('test');
选项[0]。值='1';
elSel.options[0]。文本='新值';
elSel.selectedIndex=0;
}
-选择一个项目-
尝试使用DOM操作:
<select id="mySelect">
<option value="">Please select</option>
</select>
<script>
var elSel = document.getElementById('mySelect');
var opt = {};
opt = document.createElement('option');
opt.value = '1';
opt.text = 'a';
elSel.appendChild(opt);
opt = document.createElement('option');
opt.value = '2';
opt.text = 'b';
opt.selected = true; /* Here is where we update the select element */
elSel.appendChild(opt);
opt = document.createElement('option');
opt.value = '3';
opt.text = 'c';
elSel.appendChild(opt);
</script>
请选择
var elSel=document.getElementById('mySelect');
var opt={};
opt=document.createElement('option');
opt.value='1';
opt.text='a';
艾瑟尔·阿佩奇尔德(opt);
opt=document.createElement('option');
opt.value='2';
opt.text='b';
opt.selected=true;/*这里是我们更新select元素的地方*/
艾瑟尔·阿佩奇尔德(opt);
opt=document.createElement('option');
opt.value='3';
opt.text='c';
艾瑟尔·阿佩奇尔德(opt);
在这里测试它:
问题是我使用的jQuery插件(Uniform),我没有意识到我必须运行$.Uniform.update()
在哪里/如何执行JS?当他们单击按钮时JS正在执行问题是当他们单击按钮时JS正在执行。所以它不可能在加载时发生,也不可能像第二个例子那样总是发生。很抱歉没有在前面指定此项。实际上,它确实可以正常工作。我已经发布了整个代码示例供您尝试,也在Chrome和最新版本的Firefox中进行了测试。有趣的是,它对我不起作用。我应该补充的是,在添加元素之前,它被禁用(因为css)。然而,我发现在添加代码之前加上.disabled=false和在添加代码之后加上.disabled=false没有区别;塔巴扎:你的代码确实有效,我把它缩小到我使用的jquery插件中的一个问题。谢谢
<select id="mySelect">
<option value="">Please select</option>
</select>
<script>
var elSel = document.getElementById('mySelect');
var opt = {};
opt = document.createElement('option');
opt.value = '1';
opt.text = 'a';
elSel.appendChild(opt);
opt = document.createElement('option');
opt.value = '2';
opt.text = 'b';
opt.selected = true; /* Here is where we update the select element */
elSel.appendChild(opt);
opt = document.createElement('option');
opt.value = '3';
opt.text = 'c';
elSel.appendChild(opt);
</script>