2012-05-07 45 views
0

當我沒有一個類或任何東西我的XML解析正在經歷和循環,但我現在試圖使用jQuery手機的樣式。我必須以這種方式創建列表,以便樣式在加載後由jquery應用。但它只是將第一個結果加載到列表中。如果我警告$(this).text(),我會得到5個正確答案。但下面的代碼不起作用。jQuery手機創建表沒有正確地通過xml循環

$(document).ready(function() { 

          $.ajax({ 
            type: 'GET', 
            url: 'test.xml', 
            dataType: 'xml', 
            success: function(xmlDoc) { 
            var $xml = $(xmlDoc); 
            $xml.find('FirstName').each(function() { 
                   $("#list").html('<li ><a href="acura.html">' + $(this).text() + '</a></li>'); 
                   $("#list").listview('refresh'); 
                   }); 

            } 
            }); 



      }); 

繼承人的HTML:

<body> 
     <div data-role="page"> 

      <div data-role="header"> 
       <h1>Deep Web</h1> 
      </div><!-- /header --> 

      <ul id="list" data-role="listview"></ul><!-- /content --> 

      <div data-role="footer"> 
       <h4>Footer content</h4> 
      </div><!-- /footer --> 

     </div> 
    </body> 

回答

1
$("#list").html('<li ><a href="acura.html">' + $(this).text() + '</a></li>'); 

在這裏,你要設置在每個循環新的HTML,

變化是這樣的,

$("#list").append('<li ><a href="acura.html">' + $(this).text() + '</a></li>'); 
1

.html(SONETHING)與做同樣的事情ing .empty().append(SOMETHING)。而你應該這樣做的是緩衝你將追加到DOM並一次追加所有內容,因爲這是一個昂貴的過程。

      $.ajax({ 
           type: 'GET', 
           url: 'test.xml', 
           dataType: 'xml', 
           success: function(xmlDoc) { 
            var $xml = $(xmlDoc), 
             out = [];//create array to buffer output 
            $xml.find('FirstName').each(function() { 

             //add this index to the buffer array 
             out.push('<li ><a href="acura.html">' + $(this).text() + '</a></li>'); 
            }); 

            //select the #list element only once, replace the HTML all at once, then refresh 
            $("#list").html(out.join('')).listview('refresh'); 

           } 
         }); 

看看一個數組是如何被用來存儲一堆被串起來的HTML字符串的。另外,如果您只想添加新的列表項而不是覆蓋現有的列表項,則可以用.append()替換.html()

Docs for .append()http://api.jquery.com/append