开发者

how to determine which button has been clicked in jquery

开发者 https://www.devze.com 2023-03-02 14:32 出处:网络
I\'m using a php loop to generate multiple button elements. How can I determine which button has been clicked by 开发者_开发问答using jquery?

I'm using a php loop to generate multiple button elements. How can I determine which button has been clicked by 开发者_开发问答using jquery?

<script type="text/javascript">

$(function(){

    if(button.click){
        alert(button.id);
    }

});

</script>

<?php for($x=0; $x<4; $x++){ ?>
<ul id="x">
<li><input type="button" id="<?php echo $x; ?>" value="<?php echo $x; ?>"/></li>
</ul>
<?php } ?>


The most common way to identify a element is id. (Literally, id does mean "identification")

The way you want it, should be something like this.

$("input").click(function() { //This will attach the function to all the input elements
   alert($(this).attr('id')); //This will grab the id of the element and alert. Although $(this).id also work, I like this way.
});

However, generalizing the bind to all the input elements might be a bad idea. So try giving a common class to specific elements and use $(".yourclass") instead.


well, if your code looks like the below

$('input:button').click(function(){
   $(this); //this will always refer to the clicked button. 
            //You can use traversal to find stuff relative to this button
   var butId = $(this).attr('id'); //this will give you the ID of the clicked button
});


<?php for($x=0; $x<4; $x++){ ?>
<ul id="x">
<li><input type="button" id="<?php echo $x; ?>"  value="<?php echo $x; ?>"/></li>
</ul>
<?php } ?>

<script type="text/javascript">
    $("input").click(function() {
        clickButton(this) // this is the button element, same as alert(this.id)
    });

    function clickButton(button) {
        alert(button.id)
    }
</script>

EDIT: binding per JS is preferred


$(function() {
    $("input[type='button']").click(function(event) {
        //event.target is the html causing the event
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消