gpt4 book ai didi

javascript - 获取调用 JS 函数的 HTML 文档的名称

转载 作者:可可西里 更新时间:2023-11-01 13:17:17 25 4
gpt4 key购买 nike

我是 JS 的初学者。我在网站上使用一些 JavaScript,我只想使用 1 个 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,然后稍微使用它来获取我想要的字符串,但我不确定这是否是更好的方法。

如果有更好的建议就更好了。

最佳答案

首先,出于以下几个原因,我真的建议您在 html 文档中为仅在该页面上使用的功能和单独文件中的常用功能创建单独的脚本标签:

  • 无代码污染
  • 易于改变
  • 较小的下载

其次,您可以在 window.location.pathname DOM 变量上使用 switch,它是域之后的所有内容而不是主页等。

url = vader.samplesite.com/light/saber/

window.location.pathname =/light/saber/

(查看http://www.developertutorials.com/questions/question/q-242.php)

关于javascript - 获取调用 JS 函数的 HTML 文档的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5452919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com