JavaScript没有在jsfiddle.net上运行

Lea*_*cim 74 html javascript jsfiddle

下面的代码适用于实时网站,但我不能让它在网站jsfiddle上运行.

例如,见这个.

任何人都可以告诉我为什么它不适用于jsfiddle

在控制台上它记录:ReferenceError: fillList is not definedReferenceError: 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);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

med*_*iev 92

您定义的函数在onload函数中定义,因此在它们可引用之前,因为它们在该函数中定义,所以它们只能在该函数内引用.您可以在HTML中将它们作为全局变量引用.你有三个选择

一)(最简单,最快捷,不理想) -改变function blah(){}window.blah = function(){};使函数全局.

b)(理想方式) - 使用不显眼的Javascript将行为附加到JS中的DOM元素,这意味着单独的HTML与JS.

c)让jsfiddle不要包装东西.更改onLoad无包装(躯干或头部).

所以不要只在JS中<p onclick="lol()" id="foo">var e = document.getElementById('foo'); e.onclick = lol;.

我推荐b,因为它鼓励最佳实践.

  • 因为功能未在实时站点上的另一个功能中定义.jsfiddle将你的JS抛出一个函数.在http://fiddle.jshell.net/mjmitche/afPrc/show/上查看源代码 (5认同)
  • 谢谢.但是,这种解决方法是必需的,这是非常荒谬的. (4认同)

mVC*_*Chr 49

在您的小提琴中选择no wrap (head)左侧的下拉列表,单击"运行",它将起作用.

见例→

onLoad选择何时,您的功能仅在闭包中定义$(document).ready(function() {});.


Don*_*n D 5

我发现了同样的问题并通过更改Load TypeJavaScript设置来解决它:

No wrap-in<head>或者No wrap-in<body>在下拉JavaScript设置菜单中.请参考下图.

JavaScript设置菜单