Get id of element on button click using jquery

后端 未结 3 546
自闭症患者
自闭症患者 2020-12-31 21:50

i have list of dynamic generated buttons and id is generated on run time. how can is get id of clicked button using JQuery.

Here is js code

var btn         


        
相关标签:
3条回答
  • 2020-12-31 22:21

    You should add click event of the button after document is ready(Loaded):

    $(document).ready(function(){
        $("#btnDel").click(function() {
            alert('Button clicked.');
        });
    });
    
    0 讨论(0)
  • 2020-12-31 22:27
    $('.generatedButton').click(function() {
      alert(this.id);
    });
    

    EDIT after you posted the code:

    var btn = 
      $("<input type='button' value='Delete' />")
        .attr("id", "btnDel" + $("#hid").val())
        .click(function() {
           alert(this.id);
        });
    $("body").append(btn);
    
    0 讨论(0)
  • 2020-12-31 22:34

    For your example it would be like this:

    $("#btnDel").click(function() {
      alert(this.id);
    });
    

    Note that you can't loop the code you have, IDs have to be unique, you'll get all sorts of side-effects if they're not, as it's invalid HTML. If you wanted a click handler for any input, change the selector, like this:

    $("input").click(function() {
      alert(this.id);
    });
    
    0 讨论(0)
提交回复
热议问题