2014-02-12 36 views
0

我有以下之外定義?這有什麼問題?變量不是。每個功能

+0

JavaScript是函數作用域語言,只是在每個循環之前聲明html。順便說一句,你的語法是錯誤的每個循環在這裏 –

+1

也可能錯字:關閉每個函數'});' – Anton

回答

6

有幾件事情在你的代碼來解決:

  • 您需要聲明傳遞的功能以外的變量到each()
  • 如果您追加到字符串,您將需要+=運算符。
  • 您正試圖從DOM對象的字符串中創建一個jQuery對象爲append();只需追加字符串。
  • 您沒有關閉您的each()方法。 (由Anton斑)
success: function (xml) { 
    var html = ''; 
    $(xml).find('persons').each(function(){ 
     html += '<div class = .... things here>' 
    }) 
    $('body').append(html); 
} 
1

它是函數的局部變量,因此無法在外部訪問。

success: function (xml) { 
    $(xml).find('persons').each(function(){ 
    var html ='<div class = .... things here>' //scope is limited to each function block 
    } 
    $('body').append($(html)); // not accessible here 
} 

讓您的可變全球

不使用var關鍵字成爲全球


success: function (xml) { 
    var html; //make it global. 
    $(xml).find('persons').each(function(){ 
     html +='<div class = .... things here>'; 
    } 
    $('body').append($(html)); // not accessible here 
} 
+1

這裏'html'附加它仍然是未定義的。每個循環的匿名函數創建自己的作用域 –

1

這顯然與變量如何通過代碼查看做。簡單化有兩種類型,全球和本地。一小段代碼來解釋。

var ThisWillBeGlobal = 'hello'; 
$(document).ready(function(){ 
    // Here I can access 'ThisWillBeGlobal ', because it has been defined out of the loop 
    console.log(ThisWillBeGlobal); // Proof :) 

    var definedInsideOfFunction = 'Magic right here'; 
    console.log(definedInsideOfFunction); // This will work. Defined in functions, usable in function 
}); 
// This will work: 
console.log(ThisWillBeGlobal); // it has been defined outside the functions 

// This wont work, because it's not globally defined, it only exists in the function above 
console.log(definedInsideOfFunction); 

在你的代碼,這將使這一點:

success: function (xml) { 
    var html; // By creating the var out of the loop, it's global. 
    $(xml).find('persons').each(function(){ 
    html ='<div class = .... things here>'; // don't define var here, it won't be accessable outside this looped function 
    } 
    $('body').append(html); 
} 
2

你宣佈你在.each功能vairable試試這個:

success: function (xml) { 
    var html = ""; 
    $(xml).find('persons').each(function(){ 
    html ='<div class = .... things here>' 
    } 
    $('body').append($(html)); 
} 
2

你需要做的變量HTML全球或要使用外循環它和追加,您將需要+= operator.some這樣:

success: function (xml) { 
var html =""; 
$(xml).find('persons').each(function(){ 
html +='<div class = .... things here>' 
} 
$('body').append($(html)); 
}