2013-07-15 82 views
0

我现在可以读取XML的唯一方法是将函数添加到“解析”函数中,但我希望能够在该函数之外添加函数。当我点击匹配按钮没有任何反应。尽管解析函数内部的功能工作。我看大多数人使用,而不是“文件”,“XML”,但是当我添加XML,而不是文件我得到错误“的ReferenceError:XML没有定义”。阅读XML JS - jquery

我想在解析函数外部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> 

回答

0

问题是在click处理程序documentwindow.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')); 
    }); 
}); 
+0

大再次感谢阿伦! – user2238083

0

我想你可能会忘记文件传递给你的函数

试试这个

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