JQuery绑定多个同名ID

JQuery bind on multiple same name ID

我有一个 table 由 PHP

生成
<div class="mailbox-list">
    <ul>
    <?php while ($row=$database->fetch_array($result)){?>
        <li id="emal_new" name="<?php echo $row["id"];?>">
            <a href="#" >
            <div class="mail-checkbox">
                <input class="filled-in" id="<?php echo $row["id"];?>" type="checkbox">
                <label for="<?php echo $row["id"];?>"></label>
            </div>
            <h5 class="mail-author">VPN Access Manager</h5>
            <h4 class="mail-title"><?php echo $row["naslov"]; ?></h4>
            <p class="hide-on-small-and-down mail-text">
            <?php $poruka_kratka = clear_mail($row['poruka']);
            echo text($poruka_kratka,"75")?></p>
            <div class="position-top-right p f-12 mail-date"><?php echo $row["datum"]; ?></div>

            </a>
        <div id ="user-result" />
        </li>

    <?php }?>  
    </ul>
</div>

我的 JQCODE 是:

<script>
$(document).ready(function() {
var x_timer;    
$("#emal_new").bind('click', function (e){
clearTimeout(x_timer);
var email_id = $(this).attr("name");
x_timer = setTimeout(function(){
check_email_id_ajax(email_id);
}, 100);
});


function check_email_id_ajax(email_id){
$("#user-result").html('<img style="width: 24px; height:24px;" src="<?php echo WWW; echo 'includes/themes/'.THEME_NAME.'';?>/img/ajax.gif" />');
$.post('ajax/mailbox.php',{'email_id':email_id}, function(data) {
$("#user-result").html(data);
});
}

});
</script>

而且我在 table 中有大约 30 多条数据,而且只有在 table 中才与 jquery 绑定一起使用?绑定如何作用于所有

  • 个对象?

    当我单击 table 中的某行时,我需要调用 ajax 以获取有关按名称调用的该行的更多信息。

    谢谢!

  • 这是预期的行为,因为 HTML 中的标识符必须是唯一的,使用通用的 class 绑定事件处理程序,我也建议您使用 data-* 前缀自定义属性存储任意数据,可以使用 .data()

    访问

    将HTML改为

     <li class="emal_new" data-name="<?php echo $row["id"];?>">
         <div class="user-result"></div>
     </li>
    

    脚本

    $(document).ready(function() {
        var x_timer;
        $(".emal_new").on('click', function(e) {
    
            var email_id = $(this).data("name");
          var userResult = $(this).find('.user-result')
    
            if (x_timer)
                clearTimeout(x_timer);
            x_timer = setTimeout(function() {
                check_email_id_ajax(email_id);
            }, 100);
        });
    
    
        function check_email_id_ajax(userResult, email_id) {
            userResult.html(TheHTML);
    
            $.post('ajax/mailbox.php', {
                'email_id': email_id
            }, function(data) {
                userResult.html(data);
            });
        }
    });
    

    也不是 .bind() has been deprecated. It was superseded by the .on() 自 jQuery 1.7

    以来将事件处理程序附加到文档的方法