我有以下内容:
success: function (xml) {
$(xml).find('persons').each(function(){
var html ='<div class = .... things here>'
});
$('body').append($(html));
}
它说html未定义?这有什么问题?
答案 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);
}