简体   繁体   中英

JQuery shared functions for multiple .load events

I'm using the JQuery .load function to pull some paragraphs from 3 separate URLs into 3 separate divs on my main page. Then, I want to use JQuery to add functions to each of the 3 divs on the main page.

Here's a (very) simplified version of what I have now:

Page 1 :

<div class="mycontent">
<P> test </p>
</div>

Page 2:

<div class="mycontent">
<p> test </p>
</div>

Page 3:

<div class="mycontent">
<p> test </p>
</div>

Main page markup:

<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>

Main page JQuery:

$(document).ready(function(){

$(".div1").load("myurlA.aspx .mycontent p", function(){
$(".div1 p").wrapAll("<div class='x'></div>");
});

$(".div2").load("myurlB.aspx .mycontent p", function(){
$(".div2 p").wrapAll("<div class='x'></div>");
});

$(".div3").load("myurlC.aspx .mycontent p", function(){
$(".div3 p").wrapAll("<div class='x'></div>");
});

});

This works...but I'd like to use a single .wrapAll to wrap all paragraphs in all 3 divs. My actual main page has many more methods within in each .load function, and it just doesn't seem ideal to repeat the same methods. I've tried triggering my methods after the .load event, but I can't get them to work unless they're within the .load function.

Any help would be appreciated. Thank you.

Use jQuery.when :

$(document).ready(function() {
  $.when(
    $(".div1").load("myurlA.aspx .mycontent p")
    $(".div2").load("myurlB.aspx .mycontent p")
    $(".div3").load("myurlC.aspx .mycontent p")
  ).then(function() {
    $("div p").wrap("<div class='x'></div>")
  });
});

the code below is more dynamic, plus it wraps each div when its script is loaded.

 $(".div-link").each(function() { var current = $(this); var link = current.data("link"); current.load(link + " .mycontent p", function() { $(this).children("p").wrapAll("<div class='x'></div>"); console.log('loaded') }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="div-link" data-link="myurlA.aspx"></div> <div class="div-link" data-link="myurlB.aspx"></div> <div class="div-link" data-link="myurlC.aspx"></div> 

EDIT: Here's what ended up working for me:

$(".div1").load("myurlA.aspx .mycontent p", myFunction);
$(".div2").load("myurlB.aspx .mycontent p", myFunction);
$(".div3").load("myurlC.aspx .mycontent p", myFunction);

function myFunction(){

//shared methods & events//

};

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