如何使用jQuery访问动态创建的div的属性

问题描述:

I'm trying to retrieve a list of users from a simple MySQL database table, e.g., called TableA, which looks something like: Username(varchar), Level(tinyint), DateCreated(datetime).

On an html page I have a search input box, say - and underneath it I have a div, say to display the results. I have it so that when I start typing a word (to look for a username), jQuery makes makes an ajax request to a php file which queries the TableA for the usernames.

The jQuery part looks like:

$("#search_bar").keyup(function()
{
   var user = $(this).val();
   $.post('get_user.php', user_name : user, function(data)
   {
       $("#result_box").html();
   });
} 

The php script, get_user.php, again is a simple script which looks something like

<?php
$user = $_POST['user_name'];
//connect db,
$query = mysqli_query (select Username from TableA where Username like '$user%');

//IMPORTANT PART HERE, I create a <DIV> or can be  <P> and display it back
while ($row = mysqli_fetch_array($query))
{
   echo "<div id="user_info" username='".$row['Username']."'>".$row['Username']."</div>
   //I have the username as an attribute so I can make another .post request and get detailed user info.
}
?>

Now, previously using jQuery, every result that is being returned as a is being dumped in the result_box div ($("#result_box").html();). The problem I have with this is that if I have 3 users, say Mick, Mike and Mila and I start searching by typing 'M', the query returns all three (that's fine), however, when I click on a name, say the last one returned would be Mila, this will trigger another jQuery function which say for now just prints the name of the selected in a popup box - it however picks up the attribute of the first name, Mick, from the the first div that appeared there and not the one I clicked on. It's strange. If the search returns only a single entry then that's fine - however with multiple entries, regardless of which one I click, jQuery picks up only the first one.

I suspect its because the divs all have the same ID, and since they are being 'dynamically' created - jQuery just picks up the attribute (e.g., $("#user_info").attr('username') ) of the very first one or only one created?

Any help would be appreciated.

Thanks

我正在尝试从简单的MySQL数据库表中检索用户列表,例如,名为TableA,它看起来像 类似于:用户名(varchar),Level(tinyint),DateCreated(datetime)。 p>

在html页面上,我有一个搜索输入框,比如 em> - 和 在它下面我有一个div,说要显示结果。 我有它,所以当我开始输入一个单词(寻找用户名)时,jQuery make向一个php文件发出ajax请求,该文件向TableA查询用户名。 p>

jQuery部分如下所示: p>

  $(“#search_bar”)。keyup(function()
 {
 var  user = $(this).val(); 
 $ .post('get_user.php',user_name:user,function(data)
 {
 $(“#result_box”)。html(); 
  }}; 
} 
  code>  pre> 
 
 

php脚本get_user.php再次是一个简单的脚本,类似于 p>

 &lt;?php 
 $ user = $ _ POST ['user_name']; 
 //连接db,
 $ query = mysqli_query(从TableA中选择Username,其中Username类似'$ user%'); \  n 
 //重要部分在这里,我创建一个&lt; DIV&gt;或者可以&lt; P&gt;并将其显示回
while($ row = mysqli_fetch_array($ query))
 {
 echo“&lt; div id  =“user_info”username ='“。$ row ['Username']。”'&gt;“。$ row ['Username']。”&lt; / div&gt; 
 //我有用户名作为属性所以我 可以创建另一个.post请求并获取详细的用户信息。
} 
?&gt; 
  code>  pre> 
 
 

现在,以前使用jQuery,每个返回的结果都是 a被转储到result_box div($(“#result_box”)。html( ))。 我遇到的问题是,如果我有3个用户,比如Mick,Mike和Mila,我开始通过输入'M'进行搜索,查询返回所有三个(这很好),但是,当我点击一个名字时,说 返回的最后一个将是Mila,这将触发另一个jQuery函数,该函数现在只是在弹出框中打印所选的名称 - 然而它从出现的第一个div中获取名字Mick的属性 在那里,而不是我点击的那个。 真奇怪。 如果搜索只返回一个条目,那么这很好 - 但是有多个条目,无论我点击哪一个,jQuery只选择第一个。 p>

我怀疑它是因为div都具有相同的ID,并且因为它们是“动态”创建的 - 所以jQuery只是获取属性(例如,$(“#user_info”)。 attr('username'))是第一个或只有一个创建的? p>

任何帮助都将不胜感激。 p>

谢谢 p> div>

You should use jQuery data()
You should create the div like :

<div class="userLink" data-username="$row['username']"></div>

And acces it from jQuery like

    $('.userLink').on('click',function(e) {
         var username = $(this).data('username');
    }

And the attribute ID must be UNIQUE.

First off, you need to fix the issue of multiple DOM objects with the same id. Perhaps you can just use a class name. But, that probably won't fix your click issue. The click issue should be fixed by using the this reference that comes with the click event. This will tell you exactly which items was clicked on so even if there are multiple items, you can know which one was clicked on and can reference the attributes on that particular object with code like this:

$(this).attr("username");

FYI, you perhaps should use the HTML5 convention of data attributes. So, instead of an attribute of username="xxx", you would use data-username="xxx". Then, you can use:

$(this).data("username");

You can combine all these changes with delegated event handling to have a click handler like this:

Your PHP (switch to a class name and data-username attribute):

//IMPORTANT PART HERE, I create a <DIV> or can be  <P> and display it back
while ($row = mysqli_fetch_array($query))
{
   echo "<div class="userInfo" data-username='".$row['Username']."'>".$row['Username']."</div>
   //I have the username as an attribute so I can make another .post request and get detailed user info.
}

Your delegated event handling click handler in the page:

$("#result_box").on("click", ".userInfo", function(e) {
    var username = $(this).data("username");
});