简体   繁体   中英

Using JavaScript to load external HTML

I want to keep the code short and clean. So I'm importing tons of HTML files.

I have this in head:

<script> 
var loadHtml(file) {
    $("#LoadHTML").load("html/file.html"); 
});
</script>

And this in body:

<div id="LoadHTML"></div>

The problem is I have to duplicate the script for each <div> I have.
Is there a way I can make a placeholder in the script and do what I have visualized?

<!-- Head -->
<script> 
$(function(){
$("#LoadHTML").load("html/{data}.html"); 
});
</script>

<!-- Body -->
<div id="LoadHTML" data="file"></div>

How do I do it so I only have to use the script once?

You could group the elements to be loaded by a common class and use a data attribute to set the URL to target the AJAX request to, something like this:

$(".load").each(function() {
  $(this).load($(this).data('target')); 
});
<div class="load" data-target="html/file.html"></div>
<div class="load" data-target="html/foo.html"></div>
<div class="load" data-target="html/bar.html"></div>

With that being said, I would strongly suggest you use server side includes where possible instead of your current approach. Using client side requests as you are will make many more, potentially needless, requests to your server, and hence slowing it down.

Yes you can!

$("#LoadHTML").load("html/" + data + ".html");

where data is keyword of your template.

id has to be unique. You may have to generate the id name so it would be #LoadHTML1, #LoadHTML2, #LoadHTML3, etc.

Alternatively use class so it's ".LoadHTML"

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