how to trigger click event on dynamically created element in jquery

后端 未结 4 897
清酒与你
清酒与你 2021-01-12 02:18
if($(\'#term\').children().length == 0){
        $(\"#term\").append(\"
    \"); var i; for(i=1;
    相关标签:
    4条回答
    • 2021-01-12 02:33

      Try with .trigger() like

       $('#'+liId).trigger('click');
      
      0 讨论(0)
    • 2021-01-12 02:34

      do something like:

      $("#term").append("<ul id='ulDynamic' class='ulDynamic'></ul>");
              var i;
              for(i=1;i<=3;i++){
                  var liDynamic = "Term "+i;
                  var liId = "Term"+i;
                  var $li = $("<li />", {
                      "id" : liId,
                      "class" : 'listDynamic'
                  }).html(liDynamic).click(function() {
                      alert("clicked:" + this.id);
                  });
      
                  $("#ulDynamic").append($li);            
              }
      $("#ulDynamic").find("li:first").trigger("click");
      

      Demo :: jsFiddle

      0 讨论(0)
    • 2021-01-12 02:53

      I have seen your ID is starting with Term so you can use .on() to add click event on DOM that are added later.

      Exapmple

      $(document).on('click','[id^="Term"]',function(){
        //code here
      });
      
      0 讨论(0)
    • 2021-01-12 02:57

      use event delgation on inside your ready function

      try this

       $(function(){
         $('#term').on('click','li:first',function(){
          //do your stuff
         });
       });
      
      0 讨论(0)
    提交回复
    热议问题