Home > Enterprise >  How do I get the index of an appended object in jQuery
How do I get the index of an appended object in jQuery

Time:02-11

$("input").keypress(function(e){
    let value = $("input").val()
    if(e.which == 13 && value != ""){
        $("input").val("")
        $(".itemCategRow:nth-child(1)").append("<div class=\"button\">"   value   "</div>")
    }
})

$(".button").clicked(function(){
    alert($(this).index())
})

nothing happens when I click the buttons, the reason for getting their certain indexes is to remove certain buttons.

CodePudding user response:

Since the button is added dynamically, you can only listen to events on it through "event delegation". Try this

$(document).on("click", ".button", function(){
    alert($(this).index())
})
  • Related