我有以下之外定義?這有什麼問題?變量不是。每個功能
0
A
回答
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));
}
相關問題
- 1. 增量變動的變量的每一個功能運行
- 2. 全局變量不是內部功能
- 3. JavaScript中,變量不是由功能
- 4. 玉 - ID和變量在每...在功能
- 5. PHP變量不能改變功能
- 6. 變量不的功能
- 7. 功能不給變量
- 8. 每個功能
- 9. 變量被分配的功能,而不是一個值
- 10. 功能不期望改變的變量
- 11. 功能不改變全局變量
- 12. 我不能使用變量功能
- 13. 功能中不能使用變量
- 14. 保持變量不變,從功能的功能
- 15. 如何爲動態「每個」功能使用靜態變量?
- 16. 無功能「for循環」用於尋址每個變量的類
- 17. PhP郵寄功能每個變量輸入的新行
- 18. 每個不更新變量
- 19. Specflow:每個功能
- 20. 在每個功能
- 21. 所有功能的變量是全球
- 22. 功能不是作爲一個功能
- 23. 批量循環變量,不能cd到每個?
- 24. PHP變量變量和數組/功能
- 25. Javascript問題。變量設置功能內,但功能外它不是
- 26. 功能產生不確定的變量
- 27. 功能和不必需的變量
- 28. 功能dataTaskWithRequest不會影響變量
- 29. 功能不看變量在封閉
- 30. 子功能不可用的變量
JavaScript是函數作用域語言,只是在每個循環之前聲明html。順便說一句,你的語法是錯誤的每個循環在這裏 –
也可能錯字:關閉每個函數'});' – Anton