JavaScript no se está ejecutando jsfiddle.net


El siguiente código funciona en un sitio en vivo pero no puedo conseguir que se ejecute en el sitio jsfiddle .

Ver este por ejemplo.

¿Puede alguien decirme por qué no funciona en jsfiddle?

En la consola registra: ReferenceError: fillList is not defined y ReferenceError: mySelectList is not defined.

El código funciona como se puede ver cuando está incrustado aquí como fragmento:

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>
Author: Ruslan López, 2011-03-29

4 answers

Las funciones que define están definidas en una función onload, por lo que mientras que antes eran referenciables, debido a que están definidas en esa función, solo pueden ser referenciadas desde dentro de esa función. Usted los hace referencia como globales en su HTML. Tienes tres opciones

A) ( más fácil, más rápido, no ideal ) - cambie function blah(){} a window.blah = function(){}; haciendo que las funciones sean globales.

B) (forma ideal ) - use Javascript discreto para adjuntar comportamiento a elementos DOM desde dentro del JS únicamente, significado HTML separado de JS.

C) Hacer que el jsfiddle no envuelva las cosas onload. Cambiar onLoad a sin envoltura ( cuerpo o cabeza ).

Así que en lugar de <p onclick="lol()" id="foo"> harías var e = document.getElementById('foo'); e.onclick = lol; solo en el JS.

Recomiendo b ya que fomenta las mejores prácticas.

 86
Author: meder omuraliev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-29 06:23:11

En su violín seleccione no wrap (head) en el menú desplegable de la izquierda, haga clic en Ejecutar y funcionará.

Ver ejemplo →

Cuando se selecciona onLoad, sus funciones se definen solo dentro del cierre de $(document).ready(function() {});.

 46
Author: mVChr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-29 05:54:04

Encontré el mismo problema y lo solucioné cambiando Load Type en la configuración de JavaScript:

No wrap-in<head> o No wrap-in<body> en el menú desplegable configuración de JavaScript. Consulte la siguiente imagen.

Menú de configuración de JavaScript

 5
Author: Don D,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-01 12:06:12

Mira:

Https://stackoverflow.com/a/4935684/6796393

O es mejor ver esto:

Https://stackoverflow.com/a/19110630/6796393

Esto es lo que probé:

function testJSON() { 
    var jsonString = '{"param1":"123","param2":"XXX78","param3":"11378"}'; 
    var tmp_obj = eval('(' + jsonString + ')');
    document.getElementById("result").innerHTML =  tmp_obj.param2;
}

Y

function testJSON() { 
    var jsonString = '{"param1":"123","param2":"XXX78","param3":"11378"}'; 
    var tmp_obj = JSON.parse(jsonString);
    document.getElementById("result").innerHTML =  tmp_obj.param2;
} 

Es mejor usar el segundo enfoque.

P.d.> Vine de ¿Cómo analizar parámetros de una cadena JSON usando JS?

 0
Author: Yeldar Kossynbay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:35