选中复选框时无法检查

Having trouble checking when checkbox is checked

我正在尝试在我的站点中为一些不同的页面实现一个点赞按钮,并且我正在使用套接字 io,以便在按下点赞按钮时为每个用户更新。我有一个 like() 的简单函数,它发出 liked 然后使计数器上升并显示在页面上。但这不是问题。我决定做一个复选框,这样当复选框不受欢迎时我可以做一些事情。我也有一个有效的功能。当它未经检查时,我无法做某事。这是我用来查看复选框是否被选中的方法:

if(document.getElementById('like').checked) {
  like()
} 

虽然检查时这没有任何作用。我什至尝试用 socket.emit('liked') 替换 like() 但这也不起作用。检查复选框是否被选中的正确方法是什么? (最好没有Jquery)

Html 文件:

<!DOCTYPE html>
<html>
   <head>
      <title>Test</title>
      <meta charset="utf-8">
        <link rel="stylesheet" href="styles.css">
   </head>
   <body>
         <p id="likes">Likes: </p>
         <input type="checkbox" id="like"></input>
         <script src="/socket.io/socket.io.js"></script>
         <script>
             var socket = io.connect();
             
      if(document.getElementById('like').checked) {
        like()
      } 

             function like(){
               socket.emit('liked');
             }

       function un_like(){
               socket.emit('unliked');
             }
             
             socket.on('buttonUpdate', function(data){
                 document.getElementById("likes").innerHTML = 'Likes:  ' + data;
             });
        </script>
   </body>
</html>

addEventListener添加到复选框

var checkbox = document.querySelector("input[id=like]");

checkbox.addEventListener('change', function() {
  if (this.checked) {
    console.log("Checkbox is checked..");
  } else {
    console.log("Checkbox is not checked..");
  }
});
<input type="checkbox" id="like">Checkbox</input>

使用onChange来处理这个问题。 Additional reading

<input type="checkbox" id="like" onChange="clickHandler(this)"></input>

function clickHandler(checkbox) {
   if(checkbox.checked) {
        like()
   } 
}

示例代码:

function clickHandler(checkbox) {
   if(checkbox.checked) {
       console.log('selected')
   } else {
      console.log('unselected')
   }
}
select / unselect: <input type="checkbox" id="like" onChange="clickHandler(this)"></input>