变量未在外部定义。每个函数

时间:2014-02-12 14:17:50

标签: jquery

我有以下内容:

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

它说html未定义?这有什么问题?

5 个答案:

答案 0 :(得分:6)

您的代码中有几点需要解决:

  • 您需要在传递给each()的函数之外声明变量。
  • 如果您附加到字符串,则需要+=运算符。
  • 您正在尝试使用append()的DOM对象字符串创建jQuery对象;只需追加字符串。
  • 您尚未关闭each()方法。 (由Anton发现)
success: function (xml) {
    var html = '';
    $(xml).find('persons').each(function(){ 
        html += '<div class = .... things here>'
    })
    $('body').append(html);
}

答案 1 :(得分:2)

你在.each函数中声明你的变量试试这个:

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

答案 2 :(得分:2)

你需要将变量html设置为全局或在你想要使用它的循环之外。对于追加,你需要+= operator.something这样:

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

答案 3 :(得分: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
}

答案 4 :(得分: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);
}