简体   繁体   中英

Execute script on ajax requested page before page loads

I have a AJAX based website navigation. One is index.html other is profile.html . The content of both pages is like this:

<html>
<head>
<script src="script1.js" type="text/javascript"></script>
</head>
<body>
<nav class="main-nav">.....{{nav-content}}.....</nav>
<div class"content">
---{{main-content}}-----
</div>
</body>

On both the pages I have all the scripts linked that may be needed anywhere on website. On profile.php I have a tabs widget that is triggred using $("div#mySliderTabs").sliderTabs(); .

When I load profile.php's <div class=".content"></div> content using .load() and I have to manually execute $("div#mySliderTabs").sliderTabs(); as .load() callack again to make sliderTabs working.

Is there any way to make sliderTabs work without triggering the script again and load the resulting html <div class=".content"></div> content's only into current page.

No. SliderTabs needs a DOM element as far as i know. That means it needs to be present to be instantiated. There are other options though

  1. you could load the new content, save it in a jQuery collection and execute sliderTabs() without it being in the DOM. Then you could add it whenever you want. sliderTabs() still needs to be executed after your AJAX call though.

  2. sliderTabs could use bubbling events to make - for example - click events work. Like this:

__

$('document').on('click', '#sliderButton', function() {
    // do the sliding
});

The buttons will have their event listeners even when they're loaded with AJAX afterwards.

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