获取使用while循环生成的div的唯一ID

时间:2014-02-03 17:42:02

标签: javascript php jquery

<?php

include('config/config.php');

if($_POST)
{
    $q=$_POST['searchword'];
    $sql_res=mysql_query("select uid,username,email,media,country from select_tag where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");
    while($row=mysql_fetch_array($sql_res))
    {
        $username=$row['username'];
        $email=$row['email'];
        $media=$row['media'];
        $country=$row['country'];
        $b_username='<b>'.$q.'</b>';
        $b_email='<b>'.$q.'</b>';
        $final_username = str_ireplace($q, $b_username, $username);
        $final_email = str_ireplace($q, $b_email, $email);
        ?>
        <div class="display_box" id="display">
        <img align="top" src="<?php echo $media; ?>" style="width:40px; height:40px;"  />
        <span class="name" id="name" data-ruid="<?php echo addslashes($row[uid]); ?>" style="position: relative;top:11px;" onclick="showselected_people();"><?php echo $final_username; ?></span></div>

        <?php
    }
}
?>

所以我编辑了帖子,但现在我收到错误“使用未定义的constatnt uid”.. ???

3 个答案:

答案 0 :(得分:1)

你可以在你的范围内使用uid:

 <span class="name" id="name-<?php echo $row[uid] ?>" style="position: relative;top:11px;"><?php echo $final_username; ?></span></div>

然后在jquery中:

$(".name").on('click', function(){
    var arr = this.id.split('-');
    var id = arr[1]; //its your uid
});

答案 1 :(得分:0)

通过此代码,当您单击div时,将在userName变量中存储用户名。

  var parElem = document.getElementById('display');
    parElem.addEventListener('click', getName);
    var userName;
    function getName(){
        var allspan = this.getElementsByTagName('span'); 
        for(var i=0; i<allspan.length; i++){
            if(allspan[i].id == 'name'){
                 userName = allspan[i].innerHtml;
                break;
            }
        }
    }

答案 2 :(得分:0)

虽然@Awlad Liton的解决方案已经足够,但我通常更喜欢将这些数据放在不同的属性中。

<span class="name" id="name" data-ruid="<?php echo addslashes($row['uid']); ?>" ....

然后在JS:

$(".name").on('click', function() {
    var rowId = $(this).attr("data-ruid");
    //and maybe even clean it up
    rowId = parseInt(rowId);
});