JavaScript & HTML: Event Listener Is Not Producing Text Alert As Expected; ReferenceError: button is not defined

JavaScript & HTML: Event Listener Is Not Producing Text Alert As Expected; ReferenceError: button is not defined

我正在尝试在 DOM(网页)上实现一个事件侦听器,当用户在输入框中提交输入时它会产生警报。

这是我的 HTML 代码:

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

<head>

    <meta charset="UTF-8">
    <title>DOM Examples</title>
    <!--  <link rel="stylesheet" href="main.css"></link>  -->

</head>


<body>

    <h1 id="title">This is my Title </h1>

    <input type="text" placeholder="some text">
    <button id='submit-text-btn'>Submit</button>

    <p>
        This is the text that is going to display. 
        I really need to figure out how to balance the next week out. 
        Maybe just pour myself into this and finish recursion, classes, plus guessing game quickly. 
    </p>


    <script src="dom.js"></script>


</body>


</html>

这是我的 JS 代码:

function getInputAndUpdate(inputElement){
    const text = inputElement.value;
    inputElement.value = '';
    alert(text);
}

button.addEventListener('click', function(){

    const inputElement = document.querySelector('input');

    getInputAndUpdate(inputElement); 

});

下面是我生成的网页的屏幕截图:

我的问题是当我在输入框中键入文本并单击提交时没有任何反应。根本不会弹出警报消息。

以下是我在控制台中看到的错误:

dom.js:10 Uncaught ReferenceError: button is not defined

那是因为您要添加事件侦听器的 button 变量尚未初始化。

要获取 DOM 中元素的引用,请使用 document.getElementById (which retrieves the element that has the ID - note that IDs must be unique), document.getElementsByClassName (which retrieves all elements that have the class) or document.getElementsByTagName(通过标签名称检索所有元素)。

在这种情况下,由于您已经在按钮上使用了 ID,因此您可以使用 document.getElementById:

检索元素

function getInputAndUpdate(inputElement){
    const text = inputElement.value;
    inputElement.value = '';
    alert(text);
}

var button = document.getElementById('submit-text-btn');
button.addEventListener('click', function(){

    const inputElement = document.querySelector('input');

    getInputAndUpdate(inputElement); 

});
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">
    <title>DOM Examples</title>
    <!--  <link rel="stylesheet" href="main.css"></link>  -->

</head>


<body>

    <h1 id="title">This is my Title </h1>

    <input type="text" placeholder="some text">
    <button id='submit-text-btn'>Submit</button>

    <p>
        This is the text that is going to display. 
        I really need to figure out how to balance the next week out. 
        Maybe just pour myself into this and finish recursion, classes, plus guessing game quickly. 
    </p>


    <script src="dom.js"></script>


</body>


</html>

就像这样 select 你的按钮

const button = document.getElementById("submit-text-btn");