简体   繁体   中英

how to run call some Javascript code with jQuery as soon as element loads to page by Ajax?

I'm trying to assign some attributes to some html tags as soon as they load to the page by Ajax, but I don't want to write any Javascript in my page. foe example I have the the html like below:(remember that this comes via ajax, not on page load)

<div data-something="true">
 something here
</div>

and I want to have something like this which is saved to a .js file: (this doesn't work)

$('body').on('load', '[data-something]', function(){  
       //do something 
});

but I do NOT want to have like this in one page :

<div data-something="true">
 something here
</div>

<script>
   $(function(){
        //do something
   });
</script>

is there anyway to do so? to trigger the event as soon as the element being loaded?

Sure, put it in the success of the ajax call.

$("someelemnt").load("somepage.html",function(){
    // do something.
});

do not use script tags on a page that you are loading via ajax, they'll usually get executed before the html is appended to the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM