简体   繁体   English

将参数传递给JavaScript中的事件监听器函数

[英]Passing parameters to a event listener function in javascript

Hello I have some code in which I take user input through in html and assign it to,two global variables 您好,我有一些代码可以在其中输入用户输入的html并将其分配给两个全局变量

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

Which next show up in this addeventlistener function as parameters of the whowon function 接下来的哪个显示在此addeventlistener函数中,作为whowon函数的参数

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

The click event is meant to trigger the whowon function and pass in the parameters click事件旨在触发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();
}

}

However the values are null,as I get a cannot read properties of null error on this line 但是值是空的,因为我在这行得到一个无法读取的空错误属性

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

I am pretty sure the problem is coming from the addlistener function,any help would be appreciated 我很确定问题出在addlistener函数,任何帮助将不胜感激

Well you could do something like this - 好吧,你可以做这样的事情-

$( 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);

});

Wrap your code in $(document).ready(function(){}). 将您的代码包装在$(document).ready(function(){})中。 This will ensure that all of your DOM elements are loaded prior to executing your Javascript code. 这将确保在执行Javascript代码之前已加载所有DOM元素。

Try putting all of your code inside this 尝试将所有代码放入其中

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

   //Your code here

});

My guess is that your code is executed before the html actually finished loading, causing it to return null. 我的猜测是,您的代码在html实际完成加载之前已执行,导致其返回null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM