以下代码可在实时站点上运行,但无法在jsfiddle站点上运行。
谁能告诉我为什么它在jsfiddle上不起作用?
在控制台上,它记录:ReferenceError: fillList is not defined和ReferenceError: mySelectList is not defined。
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>
您定义的函数是在onload函数中定义的,因此在它们被引用之前,因为它们是在该函数中定义的,所以只能在该函数中引用它们。您在HTML中将它们称为全局变量。您有三种选择
a)(最简单,最快,最不理想)-更改function blah(){}为window.blah = function(){};使功能全局化。
function blah(){}
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中进行操作。
<p onclick="lol()" id="foo">
var e = document.getElementById('foo'); e.onclick = lol;
我推荐b,因为它鼓励最佳做法。