代码之家  ›  专栏  ›  技术社区  ›  Dawn17

文件getElementById即使在窗口之后也给了我未定义的属性。装载

  •  0
  • Dawn17  · 技术社区  · 7 年前

    我试图在点击按钮时弹出一条警告消息。

    window.onload = function () {
        document.getElementById("search-button").addEventListener("click", () => {
            alert(document.getElementById("input-text").value)
        })
    };
    

    这是我脚本中的内容,下面是HTML

        <div class="row" style="
                margin-top: 1.5em;
                margin-bottom: 1.5em;">
            <div class="input-group" style="width: 50%; float: none; margin: 0 auto">
                <input type="text" class="form-control" placeholder="Search" id="input-text" />
                <div class="input-group-btn">
                    <button id="search-button" class="btn btn-primary">
                        <span class="glyphicon glyphicon-search"></span>
                    </button>
                </div>
    
            </div>
        </div>
    

    我想做的是提醒我在 input 要素我以为这个问题可以通过把 window.onload 但还是一样。

    有什么帮助吗?

    2 回复  |  直到 7 年前
        1
  •  0
  •   Nidhin Joseph    7 年前

    您的代码看起来不错,但作为替代方法,您可以使用 IIFE way

    (function() {
      document.getElementById("search-button").addEventListener("click", () => {
        alert(document.getElementById("input-text").value)
      });
    })();
    <div class="row" style="
                margin-top: 1.5em;
                margin-bottom: 1.5em;">
      <div class="input-group" style="width: 50%; float: none; margin: 0 auto">
        <input type="text" class="form-control" placeholder="Search" id="input-text" />
        <div class="input-group-btn">
          <button id="search-button" class="btn btn-primary">
                        <span class="glyphicon glyphicon-search">Test</span>
                    </button>
        </div>
    
      </div>
    </div>
        2
  •  0
  •   Ion    7 年前

    你也可以把它包在盒子里 DOMContentLoaded 而不是使用窗口。onload事件时,另一个脚本可能会覆盖您的函数。

    window.addEventListener('DOMContentLoaded', (event) => {
        document.getElementById("search-button").addEventListener("click", () => {
            alert(document.getElementById("input-text").value)
        })
    });