javascript删除选择列表中的选定元素

javascript删除选择列表中的选定元素,javascript,Javascript,选择列表的HTML为: <div class="textf_rechts"> <select style="height: 14em; width: 300px" size="10" name="hersteller"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <

选择列表的HTML为:

<div class="textf_rechts">
<select style="height: 14em; width: 300px" size="10" name="hersteller">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select> </div>
但它返回的选择变量在此代码中未定义

var select = document.getElementsByTagName('select').selectedIndex;
select.removeChild(select[select.selectedIndex]);
…您正在将
select
设置为
undefined
,因为您试图访问
节点列表上的
selectedIndex
属性<代码>节点列表
没有
selectedIndex
属性。然后尝试调用
undefined
上的
removeChild

应该是这样的:

var select = document.getElementsByTagName('select')[0];
if (select && select.selectedIndex >= 0) {
    select.removeChild(select[select.selectedIndex]);
}
我们得到第一个选择框,然后如果有一个选择框,并且它选择了某些内容,我们将删除该选择项

|

试试这个

 <div class="textf_rechts">
        <select id ="select" style="height: 14em; width: 300px" size="10" name="hersteller">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
        </select> 
    </div>

它返回select.selectedIndex为undefined@user1987:不应该,请看我刚才添加的实例。@t.J.Crowder:我一直是一个stackoverflow阅读器,而不是海报,对不起!只是习惯了这里的东西。
 <div class="textf_rechts">
        <select id ="select" style="height: 14em; width: 300px" size="10" name="hersteller">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
        </select> 
    </div>
var element = document.getElementById("select");
element.options[element.selectedIndex].remove();