javascript - 访问 javascript 中内联函数内所做的变量修改

标签 javascript jquery variables scope parameters

我试图将局部变量传递给 JavaScript 中的内联函数,并让该(内联)函数操作这些变量,然后能够访问包含函数中更改的变量值。这可能吗?这是我正在使用的代码示例:

function addArtists(artist, request, origElm, xml){

//variables
var artistIdArray = [];

/*coding*/

//traverse xml
$('element', xml).each(function(){

/*coding*/ 

$.ajax({  
   /*parameters*/
   success: function(html) {
    var artistAbb = html;

    /*coding*/

    //add this element's id to the array of ids to make it draggable later
    artistIdArray.push(artistAbb);
    alert(artistIdArray[artistIdArray.length - 1]);

 }//end on success    

});//end ajax call

});//end each(function()

 alert(artistIdArray.length);

}

问题是我不断得到artistIdArray.length = 0,即使元素是几个元素在添加到数组后会被“警告”。

就像我说的,我不知道如果没有全局变量或对象是否可能。有任何想法吗?我完全错了吗?

编辑:整个函数

function addArtists(artist, request, origElm, xml){  

//variables  
var artistIdArray = [];

//create ordered list
//set new <ol>s class
var olClass = "artists"; //holds the class of new <ol>

//create id for new <ol>
var olId = "artists"; //holds the id of new <ol>

//create actual <ol> element
var ol = $('<ol></ol>').attr('id',olId)
                      .addClass(olClass)
                      .appendTo(origElm);

//create the <li> elements from the returned xml
//create class for new <li>s, (just the request minus the 's')
var liClass = request.substring(0, request.length-1);
//traverse xml
$('element', xml).each(function(){

    //create id for new <li> based on artist abbreviation
    var artist = $(this).text();        

    $.ajax({
    url: "php/artistToAbb.php", 
        data: {artist: artist}, 
        dataType: "html", 
        async: true,
        success: function(html) {
    var artistAbb = html;

        //create li           
    var li = $('<li></li>').attr('id', artistAbb)
                           .addClass(liClass)
                           .appendTo(ol);   

    //create arrow icon/button for li
    var img = $('<img />').attr('id', artistAbb + 'ArrowImg')
                          .attr("src","images/16-arrow-right.png")
                          .attr('onclick', "expand(this, '" + artistAbb + "', 'years', 'danwoods')")
                          .addClass("expImg")
                          .appendTo(li);    

    var artistTxt = $('<h2>' + artist + '</h2>')
                       .addClass("artist_txt")
                       .attr('onMouseOver', 'catMouseOver(this)')
                       .attr('onMouseOut', 'catMouseOut(this)')
                       .appendTo(li);

    //tag the ol element's class
    $($(origElm)[0]).addClass('expanded');

    //add this element's id to the array of ids to make it draggable later
    artistIdArray.push(artistAbb);
    alert(artistIdArray[artistIdArray.length - 1]);

  }//end on success     

});//end ajax call

});//end each(function()

//make newly added artist elements draggable
for(var n = 0; n < artistIdArray.length; n++){
  //new Draggable(artistIdArray[n], {superghosting: true, detached: true, onEnd: catClearHighlight});
  alert(artistIdArray[n]);
}
alert(artistIdArray.length);  
}

最佳答案

已更新:现在您已经发布了完整的代码。答案是,您根本不应该将元素存储在临时数组中,而应该在 AJAX 调用返回时为每个元素创建可拖动元素。

问题在于,虽然可以在 AJAX 回调内部访问数组,但函数末尾的代码(在each之外)会在 AJAX 调用完成之前执行,因此数组为空。如果您在调用返回时创建每个可拖动项,则不需要中间存储变量,并且可拖动项会在插入 DOM 时创建。另一种选择是使 AJAX 调用同步 {aSync: false},但这也可能会占用浏览器,直到所有元素都返回。在我看来,最好接受 AJAX 调用的异步特性并在创建每个元素时对其进行处理。

function addArtists(artist, request, origElm, xml){  

    //create ordered list
    //set new <ol>s class
    var olClass = "artists"; //holds the class of new <ol>

    //create id for new <ol>
    var olId = "artists"; //holds the id of new <ol>

    //create actual <ol> element
    var ol = $('<ol></ol>').attr('id',olId)
                          .addClass(olClass)
                          .appendTo(origElm);

    //create the <li> elements from the returned xml
    //create class for new <li>s, (just the request minus the 's')
    var liClass = request.substring(0, request.length-1);
    //traverse xml
    $('element', xml).each(function(){

            //create id for new <li> based on artist abbreviation
            var artist = $(this).text();            

            $.ajax({
        url: "php/artistToAbb.php", 
                data: {artist: artist}, 
                dataType: "html", 
                async: true,
                success: function(html) {
        var artistAbb = html;

                //create li                   
        var li = $('<li></li>').attr('id', artistAbb)
                               .addClass(liClass)
                               .appendTo(ol);   

        //create arrow icon/button for li
        var img = $('<img />').attr('id', artistAbb + 'ArrowImg')
                              .attr("src","images/16-arrow-right.png")
                              .attr('onclick', "expand(this, '" + artistAbb + "', 'years', 'danwoods')")
                              .addClass("expImg")
                              .appendTo(li);    

        var artistTxt = $('<h2>' + artist + '</h2>')
                           .addClass("artist_txt")
                           .attr('onMouseOver', 'catMouseOver(this)')
                           .attr('onMouseOut', 'catMouseOut(this)')
                           .appendTo(li);

        //tag the ol element's class
        $($(origElm)[0]).addClass('expanded');

        new Draggable(artistAbb, {superghosting: true, detached: true, onEnd: catClearHighlight});

      }//end on success     

    });//end ajax call

    });//end each(function()

}

关于javascript - 访问 javascript 中内联函数内所做的变量修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1950559/

相关文章:

jquery - 如何制作这个 jQuery/CSS 动画

javascript - 可变乘数

javascript - jQuery DataTables 日期范围样式

variables - Windows 7 环境变量在路径中不起作用

c - 为什么头文件中的变量会出错?

javascript - 正则表达式替换为正斜杠

javascript - 如何调用能够从 native 对象进行链接的原理/范式?

javascript - 忽略叠加图像上的鼠标交互

java:方法的错误时间,没有返回它应该返回的内容。

javascript - 处理postJSON的结果