我对 Node.js 还很陌生,但我会尽力解释我的问题。
因此,我正在一个电影网站上工作,以练习一下我的 node.js/express 技能,并且我基本上在网站的每个页面上都使用以下元素 (img):
带有统计信息和搜索输入的标题以及导航栏(将在每个页面上重复使用)
下面的 JS 代码是客户端操作的两个示例,我用它们导航到其他网页,然后在客户端激活 GET。
$(function () {
$('button').click(function (event) {
event.preventDefault()
// the value people enter in the search box
var search = $('.searchInput').val();
//replace spaces with _
var res = search.replace(/\s/g, "_");
//build the URL
var link = window.location.protocol + '//' + window.location.host + '/search/' + res;
// redirect to trigger GET in indexjs with specific search value
window.location.replace(link);
});
$('.lists').click(function (event) {
var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
window.location.replace(link);
})
});
我希望每个页面上都有相同的代码。我可以每次都输入相同的代码,但这会浪费时间。对于 HTML 和 CSS,我可以使用模板 (HTML) 或导入其他 CSS 文件来节省时间。客户端的JS有类似的东西吗?
最佳答案
将该代码放入文件中,例如“navigator.js”,然后将其加载到您想要使用它的每个页面的 html header 中
navigator.js:
$(function () {
$('button').click(function (event) {
event.preventDefault()
// the value people enter in the search box
var search = $('.searchInput').val();
//replace spaces with _
var res = search.replace(/\s/g, "_");
//build the URL
var link = window.location.protocol + '//' + window.location.host + '/search/' + res;
// redirect to trigger GET in indexjs with specific search value
window.location.replace(link);
});
$('.lists').click(function (event) {
var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
window.location.replace(link);
})
});
index.html
<script src="navigator.js"></script>
最后我建议你为你的按钮分配一个ID,例如“searchButton”而不是“button”
希望这有帮助
关于javascript - 在客户端重用 JavaScript 代码(node.js、express),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333920/