我已成功加载 xml,并且如果成功函数在加载 XML 后立即运行,则一切正常。但我想在选择框上发生 onChange 事件(这会更改 tmpproj 值)后获取属性的值。 当我尝试访问成功函数 checkimgs() 时,它说 $(xml) 未定义。
这可能是非常基本的问题,但我太盲目了,看不到它。
var tmpproj = '02064';
var fileurl = 'menu.xml';
$.ajax({
url: fileurl,
type: "GET",
dataType: "xml",
success: checkimgs,
error: error_func
});
// Callback results if error
function error_func(result) {
alert(result.responseText);
}
// Callback if Success
function checkimgs(xml) {
$(xml).find("item[projn="+tmpproj+"]").each(function()
{
alert ($(this).attr("projn"));
});
}
XML 如下所示:
<menu nome="stuff" tag="ldol">
<item projn="02064" nome="asdf" msg="ggg">
<foto nome=""/>
</item>
<item projn="06204" nome="xxx" msg="xxxd" />
</menu>
调用 onchange 事件:
$('#selctbox').change(function () {
tmpproj = $('#projlist option:selected').val();
checkimgs();
})
最佳答案
在此事件处理程序中:
$('#selctbox').change(function () {
tmpproj = $('#projlist option:selected').val();
checkimgs();
});
您直接调用 checkimgs
函数,而不传入任何 XML 数据作为参数,这就是您收到 $(xml) is not Defined
错误的原因。您需要在更改事件处理程序中调用 $.ajax
函数:
$('#selctbox').change(function () {
tmpproj = $('#projlist option:selected').val();
$.ajax({
url: fileurl,
type: "GET",
dataType: "xml",
success: checkimgs,
error: error_func
});
});
编辑:为了响应您的评论,为了避免每次更改时都检索文件,只需在第一次检索时将 XML 响应存储在变量中即可:
var tmpproj = '02064';
var fileurl = 'menu.xml';
var xmlContent = '';
$.ajax({
url: fileurl,
type: "GET",
dataType: "xml",
success: checkimgs,
error: error_func
});
// Callback results if error
function error_func(result) {
alert(result.responseText);
}
// Callback if Success
function checkimgs(xml) {
// Store the xml response
if(xmlContent == '')
xmlContent = xml;
$(xml).find("item[projn="+tmpproj+"]").each(function()
{
alert ($(this).attr("projn"));
});
}
然后在您的选择更改处理程序中:
$('#selctbox').change(function () {
tmpproj = $('#projlist option:selected').val();
checkimgs(xmlContent);
});
关于javascript - 选择更改后如何查询xml属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3987884/