2013-07-15 130 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')); 
}); 
});