无法在 JS 对象文字方法中获取 dom 元素

Unable to get dom element inside JS object literal method

我试图重构我创建的一个简单的 JS 插件,在参考了 JS 中的各种模式之后,考虑到我是 JS 的新手,我能够做出一些很好的努力。下面的代码是重构后的示例代码。但是我的 "selectedDom" 对象 returns 为空。从逻辑上讲,我找不到错误。请指导我。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <style>
        .cross {
            background: red;
            width: 5px;
            height: 5px;
        }

        .input-field {
            height: 20px;
            width: 100px;
        }

        .input-area {
            height: 100px;
            width: 100px;
        }
    </style>
    <script>
        var InputActions = (function () {
            "use strict";
            var options = {
                textVal: ".input-field",
                crossClass: ".cross",
                border: ".input-area",
                borderNone: "1px solid #e4e5e7",
                borderShow: "1px solid #006f9e"
            };

            function InputActions() {

            };
            InputActions.prototype = {
                selectedDom: document.querySelector(options.textVal),
                cross: function () {
                    var text = this.selectedDom.value;
                    var cross = document.querySelector(options.crossClass);
                    this.selectedDom.focus();
                    (text === "") ? cross.style.opacity = "0": cross.style.opacity = "1";
                },
                clearField: function () {
                    var input = this.selectedDom;
                    input.value = '';
                    this.cross();
                },
                focusItem: function () {
                    document.querySelector(options.border).style.border = options.borderShow;
                    this.cross();
                },
                blurItem: function () {
                    document.querySelector(options.border).style.border = options.borderNone;
                }
            };
            return InputActions;
        })();

        window.inputAct = new InputActions();
    </script>
</head>

<body>
    <div class="input-area cross">
        <input type="text" class="input-field" onclick="inputAct.focusItem()" />
    </div>
</body>

</html>

这是因为您将 script 标签放在了 head 中,它甚至在 document.body 创建之前就已执行。

要解决此问题,您可以将 script 移动到 body 的末尾,或者将其包装在函数中并在 DOMContentLoaded 事件上执行。


如果您只在 DOMContentLoaded 事件处理程序中包装实例化部分,那么您必须将查询 DOM 移动到构造函数主体。所以你的代码看起来像

// ...
function InputActions() {
    this.selectedDom = document.querySelector(options.textVal);
};
InputActions.prototype = {
    cross: function () {
        var text = this.selectedDom.value;
// ...

以及 DOMContentLoaded 处理程序部分:

document.addEventListener( "DOMContentLoaded", function () {
    window.inputAct = new InputActions();
});