在html页面中使用jquery显示json数据

时间:2014-03-25 19:40:56

标签: jquery html

<html>
<head>
<style>
.messboxcontent { display:none; background: rgba(0,0,0,.4); width: 400px; height: 100px; margin: 50px auto; padding: 15px;}
.mess_test {display: inline-block; cursor: pointer ; vertical-align: middle; width:165px; height:35px; background:blue; bottom:0px; left:144px; margin-right: 16px}
#msg_holder {overflow-x:scroll ;overflow-y: hidden; white-space: nowrap; position:fixed;height:110px; width:100%; background-color:yellow; bottom:0px;}
</style>
<script type="text/javascript" src="jquery.js" ></script>
<script>
$(document).ready( function() {
 done();
});
function done() {
      setTimeout( function() { 
      update();       
      done();
      }, 20000);
} 
function update() {
     $.getJSON("fetch.php", function(data) {   
       $.each(data.result, function(){    
        var message = this['message'];
        var name =  this['name'];
call(name, message);
 });
});
};
function call(name, message){
$("#msg_holder").append("<div class='mess_test'>"  + name +   "<div>");
$(".mess_test").click( function() {
          $('div.messboxcontent').html(' name :&nbsp;&nbsp; '+ name + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  Message &nbsp;&nbsp;:&nbsp;&nbsp; ' + message);
          $('div.messboxcontent').fadeIn();
   return false;
});
}
</script>
</head>
<body>
<div class="messboxcontent"></div>
<div id="msg_holder"></div>

</doby>
</html>

这是fetch.php文件

{"result":[{"message":"this is jaja","name":"jaja"},{"message":"this is koka","name":"koka"}]}

当我点击包含任何名称的蓝色框时,它总是会淡入最新的消息和名称。我想要的是当我点击包含jaja作为名称的框时我想要包含消息的框:这是jaja,

1 个答案:

答案 0 :(得分:0)

使用委托将事件添加到动态代码

$("#msg_holder").append("<div class='mess_test' message='"+message+"'>"  + name +   "<div>");

    $(document).on("click",".mess_test", function() {
          $('div.messboxcontent').html(' name :&nbsp;&nbsp; '+ $(this).html() + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  Message &nbsp;&nbsp;:&nbsp;&nbsp; ' + $(this).attr("message"));
          $('div.messboxcontent').fadeIn();
   return false;
});