以下代码可在实时站点上运行,但无法在jsfiddle站点上运行。
参见此示例。
在控制台上,它记录:ReferenceError: fillList is not defined
和ReferenceError: mySelectList is not defined
。
如下面的代码片段所示,代码可以正常工作:
function BetterSelect(oSelList) {
this.objSelectList = oSelList;
this.objSelectList.onchange = this.selectionChanged;
}
BetterSelect.prototype.clear = function() {
this.objSelectList.options.length = 0;
}
BetterSelect.prototype.fill = function(aValues) {
this.clear();
for (var i = 0; i < aValues.length; i++) {
this.objSelectList.options[i] = new Option(aValues[i]);
}
}
BetterSelect.prototype.find = function(strToFind, bSelect) {
var indx = -1;
this.objSelectList.options.selectedIndex = -1;
for (var i = 0; i < this.getCount(); i++) {
if (this.objSelectList.options[i].text == strToFind) {
indx = i;
if (bSelect)
this.objSelectList.options.selectedIndex = i;
}
}
return indx;
}
BetterSelect.prototype.getCount = function() {
return this.objSelectList.options.length;
}
BetterSelect.prototype.selectionChanged = function() {
alert("selection changed!");
}
var mySelectList = null;
window.onload = function() {
mySelectList = new BetterSelect(document.getElementById('theList'));
}
function fillList() {
mySelectList.fill(["one", "two", "three", "four", "five"]);
}
function findIt() {
mySelectList.find(document.getElementById('txtToFind').value, true);
}
<form action="" method="post">
<select multiple="multiple" name="Select1" id="theList" style="width: 152px; height: 226px">
</select>
<br />
<input name="Button1" type="button" value="Fill The List" onclick="fillList()" />
<input name="Button4" onclick="mySelectList.clear()" type="button" value="Clear The List" />
<br />
<input name="Button2" onclick="alert(mySelectList.getCount())" type="button" value="What's The Count?" />
<br />
<input name="Text1" type="text" id="txtToFind" />
<input name="Button3" type="button" value="Search" onclick="findIt()" />
</form>