我有两个下拉框,允许用户选择他们的年龄和Gender.These下拉框从我的数据库(PHP 5.5+ MYSQL)中提取他们的值,并使用检索到的值作为显示给用户的默认值。
dropbox的其他选项是通过在页面上运行的函数生成的。
这些职能是:
function AgeDropDown(){
var list= document.getElementById("Age");
for(var i=1;i<100;i++)
{
var opt = document.createElement("option");
opt.value= i;
opt.textContent=i;
list.appendChild(opt);
}
}
function genderlist(){
var list= document.getElementById("Gender");
var choices=["M","F"];
for(i=0;i<choices.length;i++)
{
var opt = document.createElement("option");
opt.value= choices[i];
opt.textContent=choices[i];
list.appendChild(opt);
}
}
虽然我的代码工作得很好,所有选项都会显示出来,但每当我单击dropbox来更改该值时,除了生成的选项之外,还会显示当前值和。
E.g
年龄
18
1
2
3 <---- Values shown in the select dropdown
4
5
6
性别
M
M
F
单击下拉框时,如何从显示的选项中删除默认值?
例如(我想要发生的事情,而不是上面所示的事情)。
年龄
1
2
3
4
5
6
7
性别
M
F
发布于 2014-02-17 04:42:11
你要做的就是清空div。可以将innerHTML设置为空字符串以清空div。
注:
您要做的是在div中添加/追加元素。所以你必须清除div (移除它的子部分)。
代码应该是list.innerHTML = "";
完整的代码如下:
function AgeDropDown(){
var list= document.getElementById("Age");
list.innerHTML = "";
for(var i=1;i<100;i++)
{
var opt = document.createElement("option");
opt.value= i;
opt.textContent=i;
list.appendChild(opt);
}
}
function genderlist(){
var list= document.getElementById("Gender");
list.innerHTML = "";
var choices=["M","F"];
for(i=0;i<choices.length;i++)
{
var opt = document.createElement("option");
opt.value= choices[i];
opt.textContent=choices[i];
list.appendChild(opt);
}
}
发布于 2014-02-17 04:42:52
您可以使用如下jQuery删除列表中的第一个元素:
$('#Gender').find('option').first().remove();
或者:
$('#Age').find('option').first().remove();
https://stackoverflow.com/questions/21829316
复制相似问题