简体   繁体   中英

Loading a html snippet from another html file

I want to have an external .html file, from which I will load snippets programatically, and insert them in the document at runtime. I did it like this in my index.html

<head>
   <link rel="import" href="html/html_snippets.html">
</head>

This is the example content of the html_snippets.html file

<div id="asd">
   <some stuff here>
</div>

Then after everything is loaded, I load the snippet like this

var friendSnippet = $("#asd").html();

The problem I am facing now is that I use the jQuery code in a loop, which runs several times, and the first time it always returns an undefined, but after that it's fine.

Why is that happening?

You can use the jQuery .load() function to load an html file into a certain element on the page.

$("#destinationElement").load("path/to/file.html");

This may solve the issue.

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