javascript - Uncaught ReferenceError: i is not defined -
i'm trying make for-loop base on array
var lists = [ "a", "b", "c", "d" ];
js
for ( = 0; < lists.length; i++) { // console.log(lists[i]); $(".sa-report-btn-"+lists[i] ).click(function () { $(".sa-hide-"+lists[i]).removeclass("hidden"); $(".sa-report-"+lists[i]).addclass("hidden"); }); $(".sa-hide-btn-"+lists[i]).click(function () { $(".sa-hide-"+lists[i]).addclass("hidden"); $(".sa-report-"+lists[i]).removeclass("hidden"); }); } am doing correctly ? got uncaught referenceerror: not defined can concat each loop jquery selector --> $(".sa-hide-"+lists[i]) ? curious ...
first off, sounds you're using strict mode — good! it's saved falling prey the horror of implicit globals.
there 2 issues code.
the first 1 you're missing declaration i. need add var i; above loop, e.g:
var i; ( = 0; < lists.length; i++) { // ... or
for (var = 0; < lists.length; i++) { note, though, in latter example, i variable function-wide, not limited for loop.
the second 1 more subtle, , outlined in question , answers: click handlers have enduring reference i variable, not copy of of created. when run in response click, they'll see i value lists.length (the value has when loop has finished).
in case, it's easy fix (and don't have declare i anymore): remove loop entirely, , replace array#foreach or jquery.each:
lists.foreach(function(list) { $(".sa-report-btn-" + list).click(function () { $(".sa-hide-" + list).removeclass("hidden"); $(".sa-report-" + list).addclass("hidden"); }); $(".sa-hide-btn-" + list).click(function () { $(".sa-hide-" + list).addclass("hidden"); $(".sa-report-" + list).removeclass("hidden"); }); }); if need support old browsers, can either shim array#foreach (which added in 2009, part of ecmascript5), or can use $.each (jquery.each) instead:
$.each(lists, function(index, list) { // note addition ------^ $(".sa-report-btn-" + list).click(function () { $(".sa-hide-" + list).removeclass("hidden"); $(".sa-report-" + list).addclass("hidden"); }); $(".sa-hide-btn-" + list).click(function () { $(".sa-hide-" + list).addclass("hidden"); $(".sa-report-" + list).removeclass("hidden"); }); }); note don't use index anywhere in our callback, have specify because $.each calls our callback index first argument, , value second. (which why prefer array#foreach.) have accept 2 arguments, 1 want being second one.
Comments
Post a Comment