开发者

retrieve id of a div by using attr("id"); is not working

index.php

 if (idx == 8) {
     var str="<?php echo $username1; ?>";
     document.write(str);
     jQuery.get("usermessage.php?username="+str, function(data) {
       document.write(data);
       var msgIDss = $(".messagepiece:last").attr("id");
       document.write(msgIDss);
     });
 }

usermessage.php

$username1=$_GET["username"];
$query2 = "SELECT id, message, datetime FROM messages WHERE username='{$username1}' ORDER BY id";
$result2 = mysql_query($query2,$connection) or die (mysql_error());
confirm_query($result2);
$num = mysql_num_rows($result2);

while($userinfo = mysql_fetch_array($result2)){
  $msgID= $userinfo['id'];
  echo "<div class=\"messagepiece\" id=" . $msgID . ">" . $userinfo['id'] . 
    $userinfo['message'] . "<br><span style=\"font-size:13px; color:orange;\">" . 
    $userinfo['datetime'] . "</span></div>|";       
}

My problem is document.write(msgIDss) display empty / blank value.

on index.php, I have tested document.write(data); and it works. I have tested document.write(str) and it work too, so if (idx == 8) is not the problem. I also tested open usermessage.php manually and it success display all the div(s), so usermessage.php page is not the problem. I guess the problem is on this line of code var msgIDss = $(".messagepiec开发者_如何转开发e:last").attr("id"). How to fix it?


I would guess that because you're not wrapping the 'id' attribute's value in double-quotes, the browser you are testing in does not pickup the id properly.

Try the following:

echo "<div class=\"messagepiece\" id=\"" . $msgID . "\">"


I think the problem is the id attribute is starting with a number. Using a string as prefix should fix:

echo "<div class=\"messagepiece\" id=\"message-" . $msgID . "\">" ......


You might try:

echo "<div class=\"messagepiece\" id=\"" . $msgID . "\">"

Note the added escaped quotes around the id value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜