2014-12-31 20 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> 
相關問題