[英]Javascript code of an HTML file calling jQuery on an external HTML file
我有一個 HTML 文件,它運行 javascript 代碼,除其他外,還有一些 jQuery 調用。 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 . 對此有何建議? 我對 javascript 很陌生,因此任何關於如何進行的建議都會非常有幫助。
這是一個顯示我的問題的示例。 請注意,在 HTML 代碼中,我指出了我想要分離的部分。
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 (只是感興趣的部分)
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>'
);
});
對於 HTML 代碼,我應該簡單地包含在頭部
<script>
$(function(){
$("#top-menu").load("./common/menu.html");
});
</script>
以及正文中正確的<div id="top-menu"></div>
。 我應該如何更改 javascript 代碼?
這個答案可能會有所幫助: 在 HTML 文件中包含另一個 HTML 文件。 它解釋了如何使用 JQuery 將 HTML 導入現有的 HTML。 具體來說
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
您要提取的內容需要放入“b.html”中。 要訪問添加的 HTML,您需要使用回調,如下所述: https://api.jquery.com/load/
$("#includedContent").load("b.html", function() {
alert( "Load was performed." );
});
即用影響加載的 HTML 的 JQuery 替換警報命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.