您想要做的就是使用JavaScript並使用網頁的DOM進行操作。基本上,網頁的HTML由瀏覽器解析並呈現爲元素樹。像<select>
這樣的每個HTML標籤都是樹中的一個元素。您可以使用JavaScript與此樹進行交互,方法是執行從此樹中刪除元素或將元素添加到此樹中的操作。 (請注意,樹上的預形成操作不會刷新頁面。)
在JavaScript中執行這些操作的標準化API被稱爲DOM。然而,包括我自己在內的很多人都認爲這個API非常笨重,並且不夠表達。做微不足道的事情需要大量的代碼。出於這個原因,許多開發人員不直接使用DOM,而是使用更強大的庫(如jQuery)來使他們的生活更輕鬆。
下面是一些HTML + JavaScript的示例,我認爲它們可以模仿大部分需求。理想情況下,爲了學習目的,這將純粹使用標準的W3C DOM API編寫,但由於您的問題不是那麼簡單,所以我採取了使用jQuery的方式。
的HTML:
<select id="list" multiple="multiple"></select>
<input id="removeButton" type="button" value="Remove"></input>
<div>
<input id="optionAdder" type="text"></input>
<input id="addButton" type="button" value="Add"></input>
</div>
<br>
<input id="clearButton" type="button" value="Clear All"></input>
<div>Not So Hidden: <input id="hidden" type="text"></input></div>
中的JavaScript:
// Uses jQuery to define an on document ready call back function
$(function(){
// The code in this function runs when the page is loaded
var options = []; // contains all the options
// add new option to drop-down
var addOption = function(optText) {
// Create new option element and add it to the <select> tag
$('<option></option>')
.attr('value', optText).text(optText)
.appendTo($('#list'));
};
// writes the names of all the options in the "hidden" text box
var fillHidden = function() {
$('#hidden').val('');
var hiddenText = "";
for(var i=0; i< options.length; i++) {
if(hiddenText) {
hiddenText += "; ";
}
hiddenText += options[i];
}
$('#hidden').val(hiddenText);
}
// Bind the click event of the "Add" button to add an option on click
$('#addButton')
.click(function(){
var optText = $('#optionAdder').val();
if(optText) {
addOption(optText);
}
$('#optionAdder').val('');
options.push(optText);
fillHidden();
});
// Bind the click event of the "Remove" button to remove the selected options on click
$('#removeButton')
.click(function(){
$('#list option:selected').each(function(){
var optIndex = $.inArray($(this).val(), options);
if(optIndex > -1) {
options.splice(optIndex, 1);
$(this).remove();
}
fillHidden();
});
});
// Bind the click event of the "Clear" button to clear all options on click
$('#clearButton')
.click(function(){
$('#list').children().remove();
options = [];
fillHidden();
});
});
這裏是一個jsfiddle demonstrating the code
這是非常有幫助的fsong。也感謝您的高層解釋。我過去使用過jQuery。儘管我已經避免學習很多javascripty的東西,因爲我已經設法找到代碼片段並與它們一起工作。你的解釋有助於從頭開始寫東西。無論如何+1確實。一旦我掌握了它,我可能會接受它。再次感謝! –
「這個函數中的代碼在頁面加載時運行」 - 是一個默認的js操作,當函數未被命名時對其進行加載執行? –
這不是JavaScript中的默認行爲,而是jQuery中非常方便的功能(http://docs.jquery.com/Tutorials:Introducing_$(document).ready())。請注意,這是一個簡短的手段,更長的形式是'$(document).ready(function(){...})'。使用它,所提供的函數中的代碼將在HTML解析並且DOM由瀏覽器加載後立即運行。 – fsong