将参数传递给 javascript 中的事件侦听器函数

Passing parameters to a event listener function in javascript

你好,我有一些代码,我在 html 中接收用户输入并将其分配给两个全局变量

 var spursscoref = document.getElementById("spursscore").value;
 var livscoref = document.getElementById("livscore").value;

接下来在这个 addeventlistener 函数中作为 whowon 函数的参数出现

var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);

点击事件是为了触发whowon函数并传入参数

function whowon(FirstScore, SecondScore, FirstTeam, SecondTeam) {

if (FirstScore > SecondScore) {

    FirstTeam.win();
    SecondTeam.lose();


} else if (FirstScore < SecondScore) {

    SecondTeam.win();


} else {

    FirstTeam.draw();
    SecondTeam.draw();
}

}

但是这些值为空,因为我在这一行收到无法读取空属性的错误

var spursscoref = document.getElementById("spursscore").value;

我很确定问题出在 addlistener 函数上,如有任何帮助,我们将不胜感激

你可以这样做 -

$( document ).ready(function() {     

var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
  var spursscoref = document.getElementById("spursscore").value;
  var livscoref = document.getElementById("livscore").value;
  whowon(spursscoref, livscoref, spurs, liverpool)
  }, false);

});

将您的代码包装在 $(document).ready(function(){}) 中。这将确保在执行 Javascript 代码之前加载所有 DOM 元素。

尝试将所有代码放入其中

document.addEventListener("DOMContentLoaded", function(event) {

   //Your code here

});

我的猜测是您的代码在 html 实际完成加载之前执行,导致它 return 为 null。