如何防止代码在一个页面中执行



我必须网站index.htmlindex.php和两个页面包含一个javascript文件script.js

我想执行一些代码从script.jsindex.html和其他到index.php.

这是可能的吗?

JS代码

function ChangeColor()
{
button.addEventListener("mouseover", () =>
{
button.classList.remove("red");
button.classList.add("blue");
}
)
button.addEventListener("mouseout", () =>
{
button.classList.add("blue");
button.classList.remove("red");
}
)
}
function CheckErrors()
{
//Content
}

在我以前的代码中,我想执行函数ChangeColor在两个网站,因为我有一个按钮,然而我的第二个函数,我想执行它只是在index.html,因为我有一个表单。

我该怎么做?,也许与窗口对象??

可以检查location.pathname是否等于/index.html:

function ChangeColor() {
button.addEventListener("mouseover", () => {
button.classList.remove("red");
button.classList.add("blue");
})
button.addEventListener("mouseout", () => {
button.classList.add("blue");
button.classList.remove("red");
})
}
if (location.pathname == "/index.html") {
function CheckErrors() {
//Content
}
CheckErrors();
}

最新更新