21

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>
4

2 に答える 2

-1

1 つのオプションは、ロードの成功時にスクリプトを初期化することです。

$('.test').on('click',function(){
   $('#ajaxload').load('test.html',function(){
      $('body').on('click', '.heading', function(){
          $(this).css('color','red');  
      }); 
    });
 });
于 2014-04-22T19:17:47.840 に答える