jquery - Passing Object in javascript function - Object is undefined -
i passing object function getting `"obj undefined error". have referred http://jsfiddle.net/f6fxb/2/
html:
<div class="panel accordion clearfix" id="dispdir"> <script type="text/javascript"> window.onload = function () { showfolders([{ "foldername": "eod-balance-summary", "objects": [{ "keyname": "eod-balance-formatted-2014-06-01.csv", "keyvalue": "eod-balance-summary/eod-balance-formatted-2014-06-01.csv" }], "childdirs": [] }, { "foldername": "reconciliation-activity-summary", "objects": [{ "keyname": "recon-summary-2014-04-01-2014-04-02.csv", "keyvalue": "reconciliation-activity-summary/recon-summary-2014-04-01-2014-04-02.csv" }], "childdirs": [] }]); }; </script> </div>
javascript:
folderid = 1; function showfolders(folderlist) { var markup = ""; $("#dispdir").append("<ul>"); (var = 0; < folderlist.length; i++) { var fid = "folder_" + folderid; markup = "<li id='" + fid + "'>" + folderlist[i].foldername + "</li>"; $("#dispdir").append(markup); $("#" + fid).on("click", function () { showjson(folderlist[i]); }); folderid += 1; } $("#dispdir").append("</ul>"); } function showjson(obj) { alert(obj.foldername); }
this doesn't work because of line: showjson(folderlist[i]);
i
has same value folderlist.length
. since line execute when element clicked, i
's value has been changed loop. there no block scope in javascript. because i
same length of array, folderlist[i]
undefined
. when gets passed showjson
, obj
undefined
.
to fix this, wrap anonymous function.
$("#" + fid).on("click", (function(i){ return function(){ showjson(folderlist[i]); }; })(i) );
in javascript 1.7 though, there block scopes:
for(let = 0; < folderlist.length; i++){ let j = i; $("#" + fid).on("click", function(){ showjson(folderlist[j]); }); }
Comments
Post a Comment