我使用ajax创建了一个动态内容:
$(function(){
$('#loadFeed').bind('click',function(){
$.getJSON('getData.php', function(json) {
var output="<ul id='feedsList'>";
for(var i=json.posts.length-1;i>=json.posts.length-31;i--){
output+="<li class='post'>";
output+="<div class='text' id='"+json.posts[i].id+"'>"+json.posts[i].shortmsg+"</div>";
output+="</li>";
}
output+="</ul>"
$(output).appendTo('.posts');
});
});
});
html代码:
<div class="posts">
<!--dynamic content here-->
</div>
我想点击短文本,然后文本将展开以显示整个文本。实现它的代码是:
<script>
$(".posts").on("click", ".text",function(){
var thisID = this.id;
$.getJSON('getData.php', function(json) {
alert(thisID);
$(this).replaceWith("<div class='long_text'>"+json.posts[thisID-1].msg+"<div>");
});
});
</script>
错误是
Uncaught TypeError: Cannot read property 'msg' of undefined .
我不知道为什么它将msg识别为未定义。我在getData.php中定义了msg,就像我对id,shortmsg所做的一样。这是我的getData.php:
<?php
// Connecting, selecting database
$link = mysql_connect('localhost', 'root')
or die('Could not connect: ' . mysql_error());
mysql_select_db('my_db') or die('Could not select database');
// Get Data
$query = 'SELECT * FROM feed ORDER BY feed.userID ASC';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
//create json format text from posts
$json=array();
while($row=mysql_fetch_array($result)){
$post=array('id'=>$row['userID'],'avatar'=>$row['avatar'],'postType'=>$row['postType'],'msg'=>$row['msg'],'shortmsg'=>$row['shortmsg'],'title'=>$row['title'],'type'=>$row['type'],'pic'=>$row['pic'],'link'=>$row['link']);
array_push($json,$post);
}
//display it to the user
header('Content-type: application/json');
echo "{\"posts\":".json_encode($json)."}";
// Closing connection
mysql_close($link);
return $row;
?>
谢谢!