Javascript window.onload根据页面值确定要运行的代码
我通过一个外部的.js文件在整个网站上使用window.onload函数,我通常检查我在哪个页面上,以便运行某些语句,例如:Javascript window.onload根据页面值确定要运行的代码,javascript,html,Javascript,Html,我通过一个外部的.js文件在整个网站上使用window.onload函数,我通常检查我在哪个页面上,以便运行某些语句,例如: window.onload = function() { var curPage = document.getElementById('page').value; if (curPage === "index.html") { // do something here } if (curPage === "about.htm
window.onload = function() {
var curPage = document.getElementById('page').value;
if (curPage === "index.html") {
// do something here
}
if (curPage === "about.html") {
// do something else here
}
}
“curPage”是每个html文档中输入的值
<input id="page" type="hidden" value="my-page.html" />
您可以使用:
location.pathname
它返回url中域之后的所有内容。例如,对于此页面,它是:
/questions/27956897/window onload根据页面值确定要运行的代码
它不包含查询字符串(如果存在)。
如果您只需要最后一个正斜杠后面的内容,这在本文中进行了讨论:,如果您不关心路径的其余部分,只想提取文件名,这将起作用。我使用了您显示的最后一个选项,这似乎是一个很好的解决方案。在页面开头设置变量并检查其值很容易。我想与其给出确切的页面名称,不如选择一些有意义的内容,比如“简介页面”或“sellingpage”,这样以后更容易理解
<script type="text/javascript">
var curPage = 'intropage';
</script>
var curPage='intropage';
如果您不想设置id或变量,可以使用另一种方法,即检查location.pathname或location.href以获取当前位置并采取必要的步骤。您可以尝试使用给定页面名称本身的RegExp,而不使用任何隐藏字段:
var url = window.location.pathname;
if(url.match('index.html')) {
//to do
} else if(url.match('about.html')) {
//to do
} else {
//to do
}
如果您在所有html文件中都适当地设置了它,您可以使用它。这很好,因为我可能在不同的目录中有同名的页面,例如:/update/client.php和/view/client.php。。。我也不需要在.html文件中添加任何内容。
location.pathname
<script type="text/javascript">
var curPage = 'intropage';
</script>
var url = window.location.pathname;
if(url.match('index.html')) {
//to do
} else if(url.match('about.html')) {
//to do
} else {
//to do
}