這第一個解決方案是在PHP中,因爲我更喜歡它。如果你想用JS來做,請看下面的編輯。
如果你正在使用PHP,您可以包括文件(功能),並通過該功能作爲一個參數,像這樣:
的index.php
<?php
include "topnav.php";
top("title");
?>
topnav。 PHP
<?php
function top($title) {
?>
<div id="topNav">
<!-- Other code you need here -->
<span id="title"><?= $title ?></span> <!-- put in inputted title -->
</div>
<?php
}
?>
我不使用JS/jQuery來加載資源(頁部分)爲我的網站。 PHP include()
更方便,我一直都在使用它!
編輯
現在我想想,你也許可以做一個JavaScript非常類似的事情,雖然這是稍微繁瑣。把一個函數放在JS中,並從頁面調用它。
例如:
的index.html
<script type="text/javascript">
$(function() {
$('#topnav').load('topnav.html');
$("body").append(top("title"));
});
</script>
topnav.html
<script>
// basically return (or print out) string of resource
function top(title) {
return "<div id='topNav'>" +
"<!-- Other code you need here -->" +
"<span id='title'>" + title + "</span>" +
"</div>";
}
</script>
EDIT 2:更詳細的說明(通過請求)
JS示例所做的是加載資源文件,就像您在示例中一樣。然而,它不是像你的純HTML文件,而是一個JS文件。一旦你加載它,你現在可以使用JS腳本。基本上,添加的腳本允許您使用大多數預定義的字符串,但可以添加一些變量(例如,"<span id='title'>" + title + "</span>"
允許您將title
放入其中)。
感謝您的回答。我不使用PHP。我很喜歡你說的JavaScript的情況。你能分享一個更詳細的例子嗎? – wildcolor
非常感謝。這是很好的解釋。我實際上想要傳遞標題,然後在標記中用作鏈接。例如我通過'例子'作爲標題。然後一個的href屬性更改爲href =「example.html」。我怎樣才能做到這一點? – wildcolor
然後,只需更改函數返回字符串以包含'「」'。 –