2011-04-24 74 views
2

我正在開發異步數據庫搜索工具。它目前與firefox和chrome一起使用,但與Internet Explorer(版本8)有一個巨大的呃逆。在列表中使用JQUERY不顯示JSON數據的IE8

學生可以輸入他們的潛在MCAT和GPA分數,然後jquery將他們放置在前25%或中50%的學校分類。基本上,這是一個神經過敏的學生的夢想(或噩夢)。

jquery循環遍歷JSON數據,顯示與<li>條目中的條件匹配的每個項目。再一次,它在ff和chrome中運行良好,但在Internet Explorer中它拒絕顯示列表項。但是,它會顯示正確的項目數,這意味着json數據正常運行。

在通過stackoverflow搜索後,我看到了一些關於IE如何拒絕將表元素和其他一些使用jquery的innerhtml元素放入元素的解釋(多彩,經常!)。

我想知道這是否是問題,雖然我發現this question類似的問題,我不能完全弄清楚如何適應我的項目(我是新來的JavaScript)。

任何幫助將是美好的。代碼可以在下面找到。

-samuel

$.getJSON("schoolgrabber.php?jsoncallback=?", function(data){ 
     //loop through the items in the array 
     for(var x=0; x < data.length; x++){ 
      if(MCAT >= data[x].TopPercentileMCAT && data[x].TopPercentileMCAT!=''){ 

      var li = $("<li>").appendTo("#schoollist"); 
      var school= data[x].School; 
      //add the actual information into the li using a chain event 
      //the event begins by appending an <a> tag, with the name of the school inside (text(data[x].School) 
      //then it adds a unique id, which is the iteration number the counter is on above (x) 
      //then it adds the url, and adds the school variable, which allows the schools to be clicked over to the results page 
      //then it puts all of that inside li, as declared above (slightly backwards, but hey) 
      $("<a>").text(data[x].School).attr("id",x).attr("href", "results.php?school=" + school).appendTo(li); 
      $("#schoollist li").addClass("school"); 
      var quantity = $(".school").length; 
      $('#schoolquantity').empty(); 
      $('#schoolquantity').append(quantity); 
      }} 
      }); 

回答

2

而是使用jQuery和鏈接來建立你的DOM,會轉而打造出你想要呈現的HTML的字符串,並添加完成字符串只是一個時間的。

它不僅可以修復您的錯誤,還可以獲得更好的性能。我正在做的是建立清單的完整HTML並計算數量。然後,當我完成構建HTML時,我將它添加到DOM。 IMO下面的方式也更具可讀性。請注意,我沒有測試過這一點,但你應該得到的想法:

$.getJSON("schoolgrabber.php?jsoncallback=?", function(data){ 
     //loop through the items in the array 

     var html = []; 
     var parentElement = $("#schoollist"); 
     var quantity = 0; 

     for(var x=0; x < data.length; x++){ 
      if(MCAT >= data[x].TopPercentileMCAT && data[x].TopPercentileMCAT!=''){ 
       var school= data[x].School;     
       html.push("<li class=\"school\">"); 
       html.push(" <a id=\"" + x + "\" href=\"results.php?school=" + school "\">"); 
       html.push(   data[x].School); 
       html.push(" </a>"); 
       html.push("</li>"); 

       quantity++; 
      } 
     } 

     parentElement.html(html.join("")); 
     $('#schoolquantity').html(quantity); 
}); 

請記住,每次你改變DOM的瀏覽器必須做一堆東西更新網頁。這是昂貴的。你想盡可能避免從DOM中添加/抓取,而是「批量」更改(作爲一個附註,如果你想改變DOM而不用「批處理」,請看jquery detach方法)。

祝你好運,希望這對你有用!

+0

美麗!非常感謝你的迅速和知識豐富的迴應。我一直在自學教學,並且遇到了IE的問題(加上,不知道如何正確優化,這是顯而易見的),它比你可能意識到的更有幫助,讓這個社區在我的指尖。 我必須編輯的唯一東西是標籤在學校後面的另一個「+」,否則它的工作完美。非常感謝。 – samuel 2011-04-25 01:34:38

+0

沒問題samuel :)是的,這個網站對任何語言的新手都很有幫助(當我學習javascript的時候,它對我也有很大的幫助)。當你有他們時請繼續提問! – Polaris878 2011-04-25 23:03:51