2014-09-18 23 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文件和它加载后的数据存储到目标元素通过标准的绑定功能“