下面的代码可以在实时网站上运行,但我无法让它在网站上运行jsfiddle http://jsfiddle.net .
See this http://jsfiddle.net/mjmitche/afPrc/例如。
谁能告诉我为什么它不起作用jsfiddle http://jsfiddle.net?
在控制台上记录:ReferenceError: fillList is not defined
and 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>
您定义的函数是在 onload 函数中定义的,因此在它们之前是可引用的,因为它们是在该函数中定义的,所以只能从该函数内引用它们。您可以在 HTML 中将它们作为全局变量引用。你有三个选择
a) (最简单、最快、不理想) - 改变function blah(){}
to window.blah = function(){};
使功能全球化。
b) (理想的方式)- 使用不显眼的 Javascript 将行为仅从 JS 中附加到 DOM 元素,这意味着将 HTML 与 JS 分开。
c) 让 jsfiddle 不包装 onload 的内容。改变onLoad
不包裹(身体或头部)。
所以而不是<p onclick="lol()" id="foo">
你会做var e = document.getElementById('foo'); e.onclick = lol;
仅在 JS 中。
我推荐 b,因为它鼓励最佳实践。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)