2014-12-31 72 views
0

我需要2个下拉列表名称它父母n孩子。 我已经让孩子一个隐藏的字段只显示为父值被点击。如何同时应用add()和remove()方法?

我试图同时应用添加和删除方法。 这是w3schools在各自的add()和remove()方法中的一个例子。

我如何将它们整合在一起?

// add()方法

<!DOCTYPE html> 
<html> 
<body> 

<form> 
    <select id="mySelect" size="8"> 
    <option>Apple</option> 
    <option>Pear</option> 
    <option>Banana</option> 
    <option>Orange</option> 
    </select> 
</form> 
<br> 

<p>Click the button to add a "Kiwi" option at the end of the dropdown list.</p> 

<button type="button" onclick="myFunction()">Insert option</button> 

<script> 
function myFunction() { 
    var x = document.getElementById("mySelect"); 
    var option = document.createElement("option"); 
    option.text = "Kiwi"; 
    x.add(option); 
} 
</script> 

</body> 
</html> 

//remove() method 
<!DOCTYPE html> 
<html> 
<body> 

<form> 
Select a fruit: 
<br> 
<select id="mySelect" size="4"> 
    <option>Apple</option> 
    <option>Pear</option> 
    <option>Banana</option> 
    <option>Orange</option> 
</select> 
</form> 
<br> 

<button onclick="myFunction()">Remove selected fruit</button> 

<script> 
function myFunction() { 
    var x = document.getElementById("mySelect"); 
    x.remove(x.selectedIndex); 
} 
</script> 

</body> 
</html> 

这里是网站的测试代码:

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_add

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_remove

+0

你的意思是这样的 - > ** http://jsfiddle.net/8akwtwxz/** – adeneo

+0

耶谢谢! :) @adeneo –

回答

0
<!DOCTYPE html> 
<html> 
<body> 

<form> 
    <select id="mySelect" size="8"> 
    <option>Apple</option> 
    <option>Pear</option> 
    <option>Banana</option> 
    <option>Orange</option> 
    </select> 
</form> 
<br> 

<p>Click the button to add a "Kiwi" option at the end of the dropdown list.</p> 

<button type="button" onclick="add()">Insert option</button> 
<button onclick="rem()">Remove selected fruit</button> 

<script> 
function add() { 
    var x = document.getElementById("mySelect"); 
    var option = document.createElement("option"); 
    option.text = "Kiwi"; 
    x.add(option); 
} 

function rem() { 
    var x = document.getElementById("mySelect"); 
    x.remove(x.selectedIndex); 
} 
</script> 

</body> 
</html> 
相关问题