[英]Reuse javascript code on client side (node.js, express)
I'm still new to Node.js, but I'll try to explain my problem as good as I can. 我仍然不熟悉Node.js,但我会尽力解释我的问题。
So I'm working on a movie site to practice my node.js/express skills a bit and I use the following elements (img) on basically every page of my website: 因此,我正在电影网站上工作,以练习我的node.js / express技能,并且基本上在我网站的每个页面上都使用以下元素(img):
Header with stats and search input and a navigation bar (will be reused on every page) 具有统计信息和搜索输入的标题以及一个导航栏(将在每个页面上重复使用)
The follow JS-code are two examples of actions on the client side that I use to navigate to other web pages, this then activates GET on the client side. 以下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);
})
});
I want this to be the same code on every page. 我希望每个页面上的代码都一样。 I could type the same code every time, but that would be a waste of time.For HTML and CSS I am able to use templates (HTML) or import other CSS files to save time.
我每次都可以输入相同的代码,但这会浪费时间。对于HTML和CSS,我可以使用模板(HTML)或导入其他CSS文件来节省时间。 Is there something similar for JS on the client side?
客户端的JS是否有类似的东西?
Put that code in a file, for example "navigator.js" and then load it in your html header in every page you want to use it 将该代码放入文件中,例如“ navigator.js”,然后将其加载到要使用它的每个页面的html标头中
navigator.js: 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 的index.html
<script src="navigator.js"></script>
Finally i suggest you to assign an id to your button, for example "searchButton" instead only "button" 最后,我建议您为按钮分配一个ID,例如“ searchButton”而不是“ button”
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.