简体   繁体   中英

jquery determine element id by class

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>

The buttons are created by a loop and I never know how many buttons I will have only that each will have a different id.

I would like to determine the id of the button that was clicked and I tried:

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

when a button is clicked, the alert doesn't even show so it seems it's not detecting my click. Firefox console shows no errors. Maybe $("a.small.button") is wrong, but what should it be?

Maybe your javascript code is executed too early. Try this :

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

If the buttons are created by javascript latter in the page, you must execute your code after that. Or you can use the on jQuery function on the parent of the buttons :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM