jquery按类确定元素id

jquery determine element id by class

本文关键字:元素 id jquery      更新时间:2023-10-12

my html:

<a href="#" class="small button" id = "spare_approve_button_<?php echo $i; ?>">approve</a>
<a href="#" class="small button" id = "spare_return_button_<?php echo $i; ?>">return</a>

按钮是由一个循环创建的,我永远不知道我会有多少个按钮,只是每个按钮都有不同的id。

我想确定被点击的按钮的id,我尝试了:

$("a.small.button").click(function(){
        var button_id = this.id;
        alert(button_id);
});

当一个按钮被点击时,警报甚至没有显示,所以它似乎没有检测到我的点击。Firefox控制台显示没有错误。也许$("a.small.button")是错的,但它应该是什么呢?

也许您的javascript代码执行得太早了。试试这个:

$(function() {
    $("a.small.button").click(function(){
        var button_id = this.id;
        alert(button_id);
    });
});

如果按钮是由页面中的javascript创建的,则必须在之后执行代码。或者,您可以在按钮的父级上使用onjQuery功能:

$(function() {
    // You can use a more specific parent.
    $(document).on('click', 'a.small.button' function() {
        var button_id = this.id;
        alert(button_id);
    });
});