0

我已经在这段代码上工作了一段时间,我终于被难住了,不知道该怎么做才能解决这个问题。

我有一个非常适合获取配置文件的 jquery 代码,但是当我需要返回 div 中的值时,它只显示用户的第一个配置文件,但如果用户在博客上发布的帖子不止一次,它不会显示个人资料信息。我试图为每个配置文件 div 附加更多信息以使其不同,但它仍然无法正常工作。

这是 GET 用户配置文件和返回响应的 jQuery 代码。

function showUser(str)
  {
var profileDiv = document.getElementById("profile_"+ str);
    if (str=="")
{
  return;
  }

   if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }
 else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
 {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  profileDiv.innerHTML=xmlhttp.responseText;
}
}
  xmlhttp.open("GET","getuser.php?q="+str,true);
  xmlhttp.send();
  }

这也是我用来传递信息的 PHP 脚本

"<div id=\"info\" onmouseover=\"showUser(" .$blogrow['id_user'].")\"><imgalign= \"left\" style=\"vertical-align:top;\" class=\"imgb\" height=\"41\" width=\"41\"  src=\"profilepics/".$blogrow['pic']."\" />".$blogrow['author']." <br>".$blogrow['timestamp']."<br></div><br>";
    echo "</div>";

这里也是存储信息的 div 部分

 echo "<div id=\"txtHint\"><div id=\"profile_".$blogrow['id_user']."\"></div></div>";
4

2 回答 2

0

问题取决于您的 HTML 标记,该标记无效。元素 id 在 HTML 页面中必须是唯一的,但我看到很多重复的 id ,例如#info、和#theDiv#txtHint#profile_X

快速解决您的问题的方法是将所有这些和任何其他重复 id 更改为一个类,然后使用 @Rohan Kumar 提供的 ajax 代码,但使用类选择器将内容附加到页面中用户的每个提及

function showUser(str)
{
    $.ajax({
       url:'getuser.php',
       data:{q:str},
       type:'GET',
       success:function(data){
           $(".profile_"+ str).html(data);
       }
    });
}

这绝对不是最有效或最优雅的解决方案,但我认为它会起作用。如果您要尝试改进代码,我建议将类.info的所有 div 绑定到 mouseenter 处理程序,使用数据属性来获取用户 ID,并可能维护检索到的配置文件列表,这样您就不会最终进行冗余调用到你的 php

于 2013-07-04T05:12:54.507 回答
0

使用$.ajax它会更简单,

function showUser(str)
{
    $.ajax({
       url:'getuser.php',
       data:{q:str},
       type:'GET',
       success:function(data){
          $("#profile_"+ str).html(data);
       }
    });
}

但是,在此之前您需要添加version任何jQuery

于 2013-07-04T04:41:05.757 回答