开发者

jQuery fn() isn't loading / working?

There is one div which changes frequently it's innerHTML by ajax. Once the page loads, jQuery function() works but when innerHTML changes by ajax then some functionality doesn't work. I checked the code using firebug and try to explain it in short.**

I think DOM loads the js file only when the page loaded first time and if ajax modifies innerHTML then function is not invoked somehow.What you say? what could be solution according to you? HTML page

 <body>
     <div class="_div_change"> dynamically class add by jQuery function()

        here contenet is added by ajax functionality
     </div>

     <script type="text/javascript"> 
          $(function(){
            $('._div_change').addClass('.div_class');
                 });
     </script>
    </body> 

Loading first time & class is added by fn() |only div innerHTML modified by ajax *** 
                                            |  
    <div class="_div_change div_class">     | <div class="_div_change">
       inne开发者_高级运维rHTML elements added successfully|   innerHTML elements altered successfully
    </div>                                  | </div>     


Your script is incomplete, but assuming that it looks like this:

$(function(){
        $('._div_change').addClass('.div_class');
});

...then what you're doing there is telling jQuery to run that function once when the DOM is initially loaded (calling $() with a function is a shortcut to jQuery.ready). If you want to re-run that function when you update the div's contents via ajax, you'll have to do that in your success handler on the ajax call.

You can give jQuery a function that it will call whenever any ajax call is complete, via jQuery.ajaxSuccess, which may be useful.


Yes, the code only runs once when the page loads.

The $(function(){...}); is the short form of hooking up the ready event for the document: $(document).ready(function(){...});.

If you change the DOM and want to apply the jQuery code to the new elements, you should rerun the code with the parent element as scope. Create a function with the code and a scope parameter:

function updateElements(scope) {
  $('._div_change', scope).addClass('.div_class');
}

Now you can run the function from the ready event with the document as scope:

$(function(){
  updateElements(document);
});

When you have loaded new content into an elements, lets say one with id="asdf", you can rerun the function with that element as scope, and it will apply the changes only to the newly added content:

updateElements($('#asdf'));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜