簡體   English   中英

JavaScript函數內的函數-需要了解以下代碼:

[英]Function within function in JavaScript - Need to understand this code:

我在名為render的函數中包含以下代碼。 如何在render函數之外調用str變量值?

另外,請您說明以下代碼? 我對js來說還很陌生,而head在查看以函數作為參數的函數調用時感到很痛苦。

我的理解是app.getList是一個將函數作為參數的對象? 但它沒有返回任何東西。 抱歉,我在這里迷路了。

app.getList("FieldList", function(reply){
    var str = "";
    $.each(reply.qFieldList.qItems, function(index, value) {
        str +=  value.qName + ' ';
    });
    console.log(str);
});

完整代碼:

 define(["jquery", //mashup and extension interface "qlik", //add stylesheet "text!./css/mystyle.css", "client.utils/state", "client.utils/routing" ], function($, qlik, cssContent, clientState, clientRedirect) { /*-----------------------------------------------------------------*/ // function redirect (sheetId){ // clientRedirect.goToSheet(sheetId, Object.keys(clientState.States)[clientState.state]) // } /*-----------------------------------------------------------------*/ /*-----------------------------------------------------------------*/ var render = function($elem, layout) { var html = '', app = qlik.currApp(); //get list of tab objects and insert into div app.getAppObjectList('sheet', function(arrayitem) { //for each sheet in the app, create a list item $.each(arrayitem.qAppObjectList.qItems, function(myindex, myvalue) { //include the sheet id as the list item id to be used as a reference for active sheet html += '<li id="' + myvalue.qInfo.qId + '">'; // onClick="redirect(' + value.qInfo.qId + '); //wrap anchor tag to be used by bootstrap styling html += '<a>'; //give the link the same name as the sheet html += myvalue.qData.title; html += '</a>'; html += '</li>'; }); html += '</ul></div>'; html += "<button id='myButton'> Click Me!! </button>"; console.log(arrayitem.qAppObjectList); console.log(html); //insert html into the extension object return $elem.html(html); }); /* Test Code Start from here */ app.getList("FieldList", function(reply) { var str = ""; $.each(reply.qFieldList.qItems, function(key, value) { str += value.qName + ' '; }); console.log(str); }); }; /*-----------------------------------------------------------------*/ return { /*-----------------------------------------------------------------*/ paint: function($element, layout) { console.count(); /*-----------------------------------------------------------------*/ $(function() { $element.html("#myButton").click(function() { // for(var mynum = 1; mynum <= 5; mynum++){ // alert('button test' + mynum); // }; }); }); /*-----------------------------------------------------------------*/ render($element, layout); /*-----------------------------------------------------------------*/ } }; }); 

app.getList可能是異步的 (意味着它在后台運行)。 您傳遞給它的函數是一個回調 一旦完成AJAX調用(或運行了任何異步方法),該函數將在將來的某個時間運行。

你的回調被傳遞reply ,這是從“回報”值getList() 不能從此函數外部訪問str 您只需要在該函數中使用reply和/或str做任何代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM