I have an HTML file which runs a javascript code doing, among other things, also some jQuery calls. I would like to separate a portion of my HTML code in an external file because I would like to use it as a common file among several HTML files and I would like the javascript code to be able to do the jQuery calls also to the external file. Any suggestion on this? I am quite new to javascript, thus any kind of suggestion on how to proceed would be very helpful.
Here is an example showing my problem. Note that in the HTML code I indicated the portion I would like to separate.
HTML
<html>
<head>
<title>MWE</title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script src="js/init.js">
</script>
</head>
<body>
<h1><a class="mobileUI-site-name">My website</a></h1>
<!-- PORTION TO EXTRACT: begin
<nav id="nav" class="mobileUI-site-nav">
<ul>
<li><a href="#">One</a></li>
<li><a href="#">Two</a></li>
<li><a href="#">Three</a>
<ul>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
</ul>
</li>
</ul>
</nav>
PORTION TO EXTRACT: end -->
<div> Some text here </div>
</body>
</html>
Javascript (just the portion of interest)
var x = jQuery('.mobileUI-site-name'), site_name = (x.length > 0 ? x.html() : ''),
site_nav_options = new Array();
jQuery('.mobileUI-site-nav a').each(function() {
var t = jQuery(this), indent;
indent = Math.max(0,t.parents('li').length - 1);
site_nav_options.push(
'<div class="mobileUI-site-nav-link><span class="indent-' + indent + '"></span>' + t.text() + '</div>'
);
});
For the HTML code I should simply include in the head
<script>
$(function(){
$("#top-menu").load("./common/menu.html");
});
</script>
and the proper <div id="top-menu"></div>
in the body. How should I change the javascript code?
This answer may be helpful: Include another HTML file in a HTML file . It explains how to import HTML into existing HTML using JQuery. Specifically
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
where the content you want to extract would need to be put into "b.html". To access the added HTML you would need to use a callback, as described here: https://api.jquery.com/load/
$("#includedContent").load("b.html", function() {
alert( "Load was performed." );
});
Ie replace the alert command with whatever you want to do with JQuery that affects the loaded HTML.
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.