我是JS的初学者。 我正在使用网站上的一些JavaScript,我只想使用一个JS文件来确定页面上的操作。像这样:
function registerEvents(){
NameOfHTMLDocument = //?? Get the name of the document that called registerEvents function.
switch(NameOfHTMLDocument)
{
case:"homepage":
hmp_btn = document.getElementById("hmp_btn");
hmp_btn.onclick=otherFunction;
break;
case:"otherPage":
elem = document.getElementById("elemID");
elem.onclick=fooFunction;
break;
//etc...
}
}
使用<body onload="registerEvents()">
调用此函数,该函数由所有页面“继承”。
问题是,如何获得“NameOfHTMLDocument”?因为我不想让JS在尝试获取不存在的元素时开始做奇怪的事情。
我发现我可以获取DOM的URL,然后使用它来获取我想要的字符串,但我不确定这是否是更好的方法。
如果你有更好的建议会很好。
答案 0 :(得分:2)
首先,我建议您在html文档中创建单独的脚本标记,以获取仅在该页面上使用的功能以及在单独文件中的常用功能,原因如下:
其次,你可以在window.location.pathname上使用开关DOM变量,它是域之后的所有东西 而不是主页等。
即
url = vader.samplesite.com/light/saber/
window.location.pathname = / light / saber /
(查看http://www.developertutorials.com/questions/question/q-242.php)
答案 1 :(得分:1)
在<body onload="registerEvents()">
通过事件函数传递对象this(DOM中的BODY),例如:<body onload="registerEvents( THIS )">
。
在您的函数本身中,调用您传递的对象object.ownerDocument.URL
以获取包含HMTL文档名称的URL或object.ownerDocument.title
以获取页面标题。
答案 2 :(得分:0)
window.location.pathname
你需要做的只是一些解析,但我相信你会明白这一点:)如果没有,请发表评论。