开发者问题收集

网络服务器上单击按钮时 addEventListener 出现问题

2021-06-03
203

我正在我的节点网络服务器上工作,无法让 addEventListener 通过单击我的网站的按钮来工作。我已经在 J​​S fiddle 上模拟了它,它工作得很好!

https://jsfiddle.net/dxfqj4ys/2/

我现在正试图为我在 Raspberry PI 节点上运行的实际网站实现完全相同的东西。

我的 index.html

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('/');
    socket.on('stats', function(data) {
        console.log('Connected clients:', data.numClients);
    });


document.addEventListener('click', function(){
  document.getElementById("demo").innerHTML = "Hello World!";
});


var button = document.getElementById("button1");
    button.addEventListener("click", function(event){
    document.getElementById('number1').textContent = 50;
});


</script>



<!DOCTYPE html>
<html>


<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
th, td {
  padding: 5px;
  text-align: left;    
}
</style>
</head>


<div>
  <input id="button1" type="button" value="Add">
</div>

<br>

<div class="custom-select" style="width:200px;">
  <select>
    <option value="0">Select operation:</option>
    <option value="1">RUT240</option>
    <option value="2">FMB920</option>
  </select>
</div>

<br>



<table id="t1">
<caption>Operation table</caption>
    <thead>
        <tr>
            <th>Operation code</th>
            <th>To Do</th>
            <th>Done</th>
            <th>Left</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>RUT240</td>
            <td>1000</td>
            <td>50</td>
            <td>
            </td>
        </tr>
        <tr>
            <td>FMB920</td>
            <td>555</td>
            <td>50</td>
            <td id ="number1">  
            </td>
        </tr>
    </tbody>
</table>
<p id="demo"></p>
</html>

和我的 webserver.js

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var request = require('request');

//handles get request and serves index.html
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/public/index.html');
});

server.listen(8080);




//THE FOLLOWING WILL COUNT THE NUMBERE OF CLIENTS
var numClients = 0;
io.on('connection', function(socket) 
{
    numClients++;
    io.emit('stats', { numClients: numClients });
    console.log('Connected clients:', numClients);
    socket.on('disconnect', function()
    {
        numClients--;
        io.emit('stats', { numClients: numClients });
        console.log('Connected clients:', numClients);
    });

});

从我的 .html 中可以看到,我有 2 个事件监听器,一个正在修改名为“demo”的元素,另一个应该修改 ID 为“number1”的元素。

带有“demo”的元素工作正常,但是“number1”不起作用。

当我作为客户端,打开开发者菜单,我可以看到以下错误: 在此处输入图片描述

Uncaught TypeError: Cannot read property 'addEventListener' of null
2个回答

错误表明 button 为空,这是因为您的脚本在 DOM 准备好之前执行,因此在实际按钮出现之前。

您只需等待 DOM 准备就绪,然后再执行任何需要引用页内元素的脚本:

window.addEventListener('DOMContentLoaded', () => {

  // Move your code in here

})

更多信息: Window:DOMContentLoaded 事件

Mereo4
2021-06-03

根据此答案: Javascript 元素为空

Javascript is executed by the browser as it is encountered, which means that if your snippet of code exists in the page before the HTML element, then at that point in time, the HTML element does not yet exist .

您可以重新排列代码并将脚本部分放在 HTML 代码之后,如下所示:

<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>

<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
th, td {
  padding: 5px;
  text-align: left;    
}
</style>
</head>


<div>
  <input id="button1" type="button" value="Add">
</div>

<br>

<div class="custom-select" style="width:200px;">
  <select>
    <option value="0">Select operation:</option>
    <option value="1">RUT240</option>
    <option value="2">FMB920</option>
  </select>
</div>

<br>



<table id="t1">
<caption>Operation table</caption>
    <thead>
        <tr>
            <th>Operation code</th>
            <th>To Do</th>
            <th>Done</th>
            <th>Left</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>RUT240</td>
            <td>1000</td>
            <td>50</td>
            <td>
            </td>
        </tr>
        <tr>
            <td>FMB920</td>
            <td>555</td>
            <td>50</td>
            <td id ="number1">  
            </td>
        </tr>
    </tbody>
</table>
<p id="demo"></p>
<script>
    var socket = io.connect('/');
    socket.on('stats', function(data) {
        console.log('Connected clients:', data.numClients);
    });


document.addEventListener('click', function(){
  document.getElementById("demo").innerHTML = "Hello World!";
});


var button = document.getElementById("button1");
    button.addEventListener("click", function(event){
    document.getElementById('number1').textContent = 50;
});


</script>
</html>
Christos Panagiotakopoulos
2021-06-03