函数获取javascript中未定义的值
我有一个xml文件,我想使用jquery搜索该文件中的一些值,但是我在函数内部和函数外部得到的值不同,请为我指出正确的方向。这是xml文件函数获取javascript中未定义的值,javascript,jquery,Javascript,Jquery,我有一个xml文件,我想使用jquery搜索该文件中的一些值,但是我在函数内部和函数外部得到的值不同,请为我指出正确的方向。这是xml文件 <?xml version="1.0" encoding="UTF-8"?> <plist version="1.0"> <dict> <key>ID</key> <string>B0A6EF3C-221F-4918-89C2-340B05F6A7AD</str
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>ID</key>
<string>B0A6EF3C-221F-4918-89C2-340B05F6A7AD</string>
<key>Name</key>
<string>name</string>
<key>Items</key>
<array>
<dict>
<key>Mode</key>
<integer>1000</integer>
<key>background</key>
<string>RGBA:0.000000,1.000000,1.000000,1.000000</string>
<key>Enabled</key>
<true/>
</dict>
<dict>
<key>Mode</key>
<integer>1000</integer>
<key>background</key>
<string>RGBA:0.000000,1.000000,1.000000,1.000000</string>
<key>Enabled</key>
<true/>
</dict>
</array>
</dict>
</plist>
当控件位于findvalue函数内时,它将打印正确的值,但当它转到调用函数并打印返回值时(在本例中为valueError),它将打印未定义的值它将返回未定义的值,因为您是从回调函数内返回值,因此,主函数本身不返回值 您需要将返回值设置为函数中的变量,并从主函数返回该值:
function findvalue(tag, searchkey) {
var returnValue = false;
$(tag).find('key').each(function(){
key = $(this).text();
value = $(this).next().text();
if(key == searchkey) {
alert("key = " + key + " searchkey = " + searchkey + " value = " + value);
returnValue = value; // assign to the parent functions variable
return value; // only returns to the callback function
} else {
returnValue = "No Match"; // same as above
return "No Match";
}
});
return returnValue; // this will allow you to access that value now
}
在循环过程中返回“No Match”对我来说似乎很奇怪,也许您应该简单地删除else语句,让父函数在没有找到匹配项时简单地返回
false
(默认值在顶部定义),并在显示结果时输出“No Match”(大概是在哪里输出findvalue()
)的结果。感谢您为我指明了正确的方向。是的,您是对的,其他部分不需要。现在我删除了其他部分,代码工作正常。谢谢您的帮助
function findvalue(tag, searchkey) {
var returnValue = false;
$(tag).find('key').each(function(){
key = $(this).text();
value = $(this).next().text();
if(key == searchkey) {
alert("key = " + key + " searchkey = " + searchkey + " value = " + value);
returnValue = value; // assign to the parent functions variable
return value; // only returns to the callback function
} else {
returnValue = "No Match"; // same as above
return "No Match";
}
});
return returnValue; // this will allow you to access that value now
}