2011-10-01 35 views
0

我正在加载使用加载和片段的少数选择列表的选项。jQuery加载片段一次用于几个目的

这是我有:

$(document).ready(function(){ 
     $("#select1").load("ts.xml #select1", 
       function (responseText, textStatus, XMLHttpRequest) { 
        if (textStatus == "success") { 
         alert("Loaded select 1"); 

        } 

     $("#select2").load("ts.xml #select2", 
       function (responseText, textStatus, XMLHttpRequest) { 
        if (textStatus == "success") { 
         alert("Loaded select 2"); 

        }  
    }); 

而且我的HTML看起来像这样:

<li id="select1" class="left"></li> 
<li id="select2" class="left"></li> 

其中ts.xml看起来是这样的:

<select id="select1"> 
<option>Lorem</option> 
<option>Ipsum</option> 
<option>Lorem Ipsum</option> 
</select> 
<select id="select2"> 
<option>Lorem</option> 
<option>Ipsum</option> 
<option>Lorem Ipsum</option> 
</select> 

如何加载ts.xml一次并继续检索碎片离开它?请注意,每次我检索一个片段时,我都希望在ts.xml加载时不提示成功。

非常感谢

回答

1

一次加载,缓存,然后使用缓存的版本:

$(document).ready(function(){ 
    var response; 
    $("#select1").load("ts.xml #select1", 
     function (responseText, textStatus, XMLHttpRequest) { 
      if (textStatus == "success") { 
       response = responseText; // this will be your xml response 
       // now you can use 'response' anywhere inside the doc.ready function 
      } 
     });  
}); 
+0

你能告诉我怎么回忆select2与'响应'作为xml缓存?我了解它的概念,但我不知道如何制作它,因此我问了这个问题。非常感谢 – jQuerybeast

+0

@ adeneo的答案将是实现这一目标的方法。如果您将'response'转换为jQuery对象(response = $(responseText)),那么您可以使用jQuery方法来解析它。所以,当你需要填充#select2时,你只需抓住'response'变量并对其进行处理。 – swatkins

0

我想我可能会回到基本的$就功能做这样的事情。

var xmlData; 

function getXML() { 
    $.ajax({ 
    type: "GET", 
    url: "ts.xml", 
    dataType: "xml", 
    error: function() { 
    $("#mydiv").append("<p>File Not Found!</p><br />"); 
    }, 
    success: function(xml){ 
     xmlData = $(xml); 
    } 
}); 

现在你可以在任何地方搜索数据,至少我是这么认为的,没有测试过,但看不出为什么不呢?

var Searchvalue = "Lorem"; 

xmlData.find("select1").find("option:contains('" + Searchvalue + "')").each(function(){ 
     // do something 
     });