Jquery events not working on ajax loaded content

后端 未结 2 1151
我寻月下人不归
我寻月下人不归 2020-12-14 08:57

The below code works. If there is some better way please let me know. If i use the script content which is present in test.html in the main page where I am loading test.html

相关标签:
2条回答
  • 2020-12-14 09:14

    It's because you are binding the event on document ready. You have to use a delegate in order for this to work. Like on. It's because .header isn't on the page on the page when it's loaded. So no event is attached.

    Your code should look some along the lines of this:

    $('body').on('click','.heading',function(){
         $(this).css('color','red');  
    });   
    

    It doesn't have to be body, but an element which isn't loaded after document ready, which is a parent of .heading.

    0 讨论(0)
  • 2020-12-14 09:19

    One option is to initialize your script on load success:

    $('.test').on('click',function(){
       $('#ajaxload').load('test.html',function(){
          $('body').on('click', '.heading', function(){
              $(this).css('color','red');  
          }); 
        });
     });
    
    0 讨论(0)
提交回复
热议问题