我試圖將本地變量傳遞給JavaScript中的內聯函數,並讓該(內聯)函數操縱這些變量,然後能夠訪問變化的值包含功能。這甚至有可能嗎?這裏是我正在使用的代碼示例:訪問在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);
}
好吧。使用上面的代碼,artistNum的值在循環內增加('call#1'提醒正確的artistNum),但是一旦控制又回到包含函數,修改的值將丟失('call#2'alerts'0') – danwoods 2009-12-23 03:59:37
嘗試將它作爲對象傳遞而不是單獨的值,並且應該在您查找時按「引用」進行處理。 – 2009-12-23 04:04:09
你叫#2引用一個全局'artistNum',而不是在'addArtists'內定義的本地' – 2009-12-23 04:05:22