Jquery events not working on ajax loaded content

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

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 through ajax. The script doesn't work.

<html>      <head>         <script src='jquerylocation' type='text/javascript'></script>     </head>     <body>         <div id='ajaxload'></div>         <button class='test'>load content via ajax</button>     </body>       <script>         $(function(){             $('.test').on('click',function(){                   $('#ajaxload').load('test.html');             });                     });     </script> </html> 

Test.html:

    <h1 class='heading'>Page via AJAX</h1>      <script>         $(function(){             $('.heading').on('click',function(){                 $(this).css('color','red');               });                                   });     </script> 

we have to load the script along with dynamically loaded content through ajax to work as you require.But disadvantage I felt was each time we send ajax request script loads all the time along with content. But I found only this solution. If anyone knows better solution please reply.

For example if change the code this way it wont work.

<html>      <head>         <script src='jquerylocation' type='text/javascript'></script>     </head>     <body>         <div id='ajaxload'></div>         <button class='test'>load content via ajax</button>     </body>       <script>         $(function(){             $('.test').on('click',function(){                   $('#ajaxload').load('test.html');             });              $('.heading').on('click',function(){                 $(this).css('color','red');               });                                            });     </script> </html> 

Test.html:

    <h1 class='heading'>Page via AJAX</h1> 

回答1:

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.



回答2:

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');         });      });  }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!