2013-02-07 50 views
0

我想知道如何解决我的脚本,我想有一个警报发生在你点击按钮,但它跟上发生在同一页上的XML的变化。 我会认为这个脚本会工作,当然,当我点击按钮没有任何反应。以为我会看到是否可以从更有经验的人那里得到任何意见。jquery阅读儿童XML数据

$(document).ready(function(){ 

function get_info() { 
    $.ajax({ 
     type: "GET", 
     url: "xmldata/product.xml", 
     dataType: "xml", 
     cache: false, 
     complete: function(doc) { 
      var product = $(doc.responseText).find("product").text() == 1; 
      var name = product.next().children("name").text(); 
      var cost = product.next().children("cost").text(); 
      $("#xmlalert").click(function(){ 
           alert(cost); 
      }) 
     } 
    }); 

} 
setInterval(function() { 
    get_info(); 
}, 5000); 
}); 

XML数据,如下所示:

<?xml version="1.0" encoding="utf-8"?> 
<store> 
    <product>1</product> 
    <info> 
     <name>Toy</name> 
     <cost>1196</cost> 
    </info> 
</store> 

回答

0

HTML代码

<button class="button" id="1">One</button> 
<button class="button" id="2">Two</button> 

更改你的JavaScript代码,如:

$(document).ready(function(){ 
     function get_info() { 
     $.ajax({ 
      type: "GET", 
      url: "xmldata/product.xml", 
      dataType: "xml", 
      cache: false, 
      complete: function(doc) { 
      $(".button").click(function(event){ 
       console.log($(this).attr('id')); 
       var product = $(doc.responseText).find("product").eq($(this).attr('id')-1); 
       var currentIndex=0; 
       product.each(function(index){ 
        var name = $(this).next().children("name").text(); 
        var cost = $(this).next().children("cost").text(); 
        alert(cost);  
       }); 
      }); 
     } 
     }); 

     } 
     setInterval(function() { 
      get_info(); 
     }, 2000); 
}); 

XML是

<?xml version="1.0" encoding="utf-8"?> 
<store> 
    <product>1</product> 
    <info> 
     <name>Toy</name> 
     <cost>1196</cost> 
    </info> 
    <product>2</product> 
    <info> 
     <name>Toy 2</name> 
     <cost>11962</cost> 
    </info> 

</store> 
+0

我不想问太多,但是有什么区别,什么xml文件被调用,以及它是否在子文件夹?比如你的cml.xml也是通过find(“product”)来找到的,它只能找到一个?有没有更具体的方法?因为这个XML将有多个产品,例如产品1,产品2等。 – Keleko

+0

好的,我改变了我的答案。 –

+0

谢谢,在我看到你的答案之前,我实际上已经明白了这一点,但它现在同时警告两种费用,因为我只希望它提醒一个。一个单独的按钮将是第二个。 – Keleko