正在读取XML JS-jquery

Reading XML JS - jquery

本文关键字:JS-jquery XML 读取      更新时间:2023-09-26

目前我读取XML的唯一方法是将函数添加到"parse"函数中,但我希望能够添加该函数之外的函数。当我单击"匹配"按钮时,不会发生任何事情。尽管解析函数中的函数可以工作。我看到大多数人使用"XML"而不是"文档",但当我添加XML而不是文档时,我会收到错误"ReferenceError:XML未定义"。

我想在解析函数之外的xml上运行函数。谢谢你的帮助。

JS-

 $(document).ready(function(){
$.ajax({
    url: 'data.xml',
    dataType: "xml",
    success: parse,
    error: function(){alert("Error: Something wrong with XML");}
 });
 });
 function parse(document){
 $(document).find('Swatch').each(function(){
 alert($(this).attr('name'));
 });
 }
 $('#Match').on('click', function () {
 $(document).find('Swatch').each(function(){
 alert($(this).attr('name'));
 });
 });

XML

 <?xml version="1.0" encoding="UTF-8"?>
<Fabric>
        <Swatch name="2016" title="Ruby_Red" alt="Main" match="2004, 2005, 2020, 2026, 2035"></Swatch>
        <Swatch name="2004" title="Spring_Yellow" alt="Knits"></Swatch>
        <Swatch name="2005" title="Newport_Navy" alt="Knits"></Swatch>
        <Swatch name="2006" title="Light_Purple" alt="Knits"></Swatch>
        <Swatch name="2007" title="Royal_Blue" alt="Knits"></Swatch>
        <Swatch name="2008" title="Ruby_Red" alt="Knits"></Swatch>              
</Fabric>

问题是click处理程序中的document引用了window.document对象。

parse方法中的document参数是该方法的本地参数,在退出该方法调用后将不存在。

这里的解决方案是创建一个全局变量,该变量将保存xml引用

$(document).ready(function(){
    $.ajax({
        url: 'data.xml',
        dataType: "xml",
        success: parse,
        error: function(){
            alert("Error: Something wrong with XML");
            xmldoc = undefined;
        }
    });
});
var xmldoc;
function parse(document){
    xmldoc = document;
    $(document).find('Swatch').each(function(){
        alert($(this).attr('name'));
    });
}
$('#Match').on('click', function () {
    $(xmldoc).find('Swatch').each(function(){
        alert($(this).attr('name'));
    });
});

我想您可能会忘记将文档传递给您的函数

试试这个

$('#Match').click(function(document){
$(document).find('Swatch').each(function(){
   alert($(this).attr('name'));
 });
});