2014-09-18 26 views
2

要求讀取Json對象,並將該值顯示在鼠標上方的工具提示上。 請找到http://jsfiddle.net/8WKTj/49/讀取json並顯示onmouse的動態值

下面的代碼是將JSON代碼:

jsonDataFile.js

{ 
    "Column1": "This represents transID", 
    "Column2": "This represents Spread percentage", 
    "Column3": :" Column3 title description"; 
} 

的javascript:

$(function() 
     { 
      $(".question").each(function(index) 
      { 
       $.getJSON("js/jsonDataFile.js",function(result){ 
        $.each(result, function(i, field){ 
         alert(" i: " + i +" ,"+ field); //prints i: column1 ,This represents transID 
            //i: column2 , This represents Spread percentage 
         $(this).prop('title', result[index]); 
        }); 
       }); 

      }); 
     }); 

當我鼠標懸停在列1,提示應顯示消息「This represent transID」。同樣,當鼠標懸停在第2欄上時,工具提示應該顯示「這代表傳播百分比」......我嘗試閱讀json文件並在工具提示上顯示消息,但輸出與預期不符。它沒有展示任何東西。請建議。

+0

你可以將json數據文件的完整路徑添加到jsfiddle嗎? – user145400 2014-09-18 15:55:46

回答

1

1)爲什麼你在爲每個問題閱讀來自網絡的SINGLE(!)靜態JSON? 2)絕對不要使用alert() - 它會鎖定它,因爲getJSON是異步的,而不是$(..)。2)絕對不要使用alert() - 它會鎖定JS的主線程和真正的調試 - 使用console.log或console.debug打印調試信息(!) - 看到這樣的消息U應該啓動嵌入式瀏覽器控制檯或類似FireBug

3)拆分邏輯可讀的功能類似於applyQuestion(元件,resultItem){}

在變量4)高速緩存陣列

因此,這裏是僞代碼用正常的邏輯(應該是這樣的)

$(function(){ 
    var applyQuestion = function(e, result){/* 
    here logic to setup element with item 
    and as a part of it - you can setup "mouseoverevent" with some things from result 
    */}; 
    var questionElements = $(".question"); 
    $.getJSON(url, function(result){ 
     questionElements.each(
      function(e){ applyQuestion(e,result);} 
     ) 
    }); 

})(); 

所以它更清晰,可以轉化爲在啓動人類語言」,加載JSON文件和它加載後的數據存儲到目標元素通過標準的綁定功能「