如何从包含所有页面的 JS 代码的单个 JS 文件中使用特定于某些页面的 JS 代码?

How to use JS codes which are specific to some pages from a single JS file containing JS codes for all the pages?

在我的网站上,我将所有 JavaScript 代码包含在一个文件 common.js 中。我面临的问题是我的一些 JS 代码特定于一页。所以它在另一个页面上显示错误。

例如,我有一个 ID 为 'user_icon' 的用户图标,它只出现在一个页面上,对于那个页面,一切正常,但对于另一个页面,它向我显示错误“Uncaught TypeError:无法读取 null 的属性(读取 'addEventListener') 在 common.js:11”。这意味着 JS 在另一个页面上找不到该元素。那么,我该如何解决这个问题?非常感谢任何建议。

这是用户图标的代码

var user_icon = document.getElementById('user-icon');
var menu = document.getElementById('menu');
var x = -100;
user_icon.addEventListener('click', function () {
    if (x == -100) {
        x = 0
        menu.style.right = x;
        menu.style.opacity = 1;
    }
    else {
        x = -100
        menu.style.right = x + '%';
        menu.style.opacity = 0;
    }
})

当您删除 DOM 绑定了事件的内容时,您必须在删除内容之前删除这些事件。

您可以通过触发 bindEventunbindEvents 来实现:


window.onload = bindEvents

var menu = document.getElementById('menu');
var x = -100;

function bindEvents() {
  var user_icon = document.getElementById('user-icon');
  user_icon.addEventListener('click', myAction, true);
}

function unbindEvents() {
  var user_icon = document.getElementById('user-icon');
  user_icon.removeEventListener('click', myAction, true);
}

function myAction() {
    if (x == -100) {
        x = 0
        menu.style.right = x;
        menu.style.opacity = 1;
    }
    else {
        x = -100
        menu.style.right = x + '%';
        menu.style.opacity = 0;
    }
}

您可以在适当的时候自由调用 bindEventsunbindEvents,但请记住,调用它们时您的元素必须在 DOM 中。否则,您会在页面上留下一些僵尸事件,这是严重的内存泄漏,尤其是在构建单页应用程序时。

你可以为此添加一个陷阱。那应该消除 Uncaught TypeError 错误。

var user_icon = document.getElementById('user-icon');
var menu = document.getElementById('menu');
var x = -100;
if(user_icon && menu)
{
    user_icon.addEventListener('click', function () {
        if (x == -100) {
            x = 0
            menu.style.right = x;
            menu.style.opacity = 1;
        }
        else {
            x = -100
            menu.style.right = x + '%';
            menu.style.opacity = 0;
        }
    })
}