我是JS的初学者。 我正在使用网站上的一些JavaScript,并且我只想使用JS的1个文件来确定页面之外的操作。事情是这样的:获取调用JS函数的HTML文档的名称
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,然后使用它来获取我想要的字符串,但我不确定这是否是更好的方法。
如果你有更好的建议,这将是很好的。
你想获得调用函数的页面的URL? – 2011-03-27 22:34:29
我试图避免使用URL,得到这个你可以使用:location.pathname.split('/')。pop();你会得到一个字符串数组,然后“玩”一下它,或者获得一个document.URL。 – ElHacker 2011-03-27 22:38:22