【问题标题】:How can I add a parameter into function, that is inside EventListener? [duplicate]如何在 EventListener 内部的函数中添加参数? [复制]
【发布时间】:2020-07-18 07:41:26
【问题描述】:

我的想法是用 vanila JS 编写一个计算器,但我遇到了一个问题。我想通过绑定键来解决它,并分别为它们中的每一个添加事件监听器。为了不重复我的代码,我想创建一个可以做所有事情的函数,我只添加一个键号作为参数。当我运行代码时,它会立即触发该函数,而无需单击 "number two" 。我知道,问题出在“点击”,getInput(二),我想让这个功能工作。有什么想法吗?

let input = document.getElementById("input").innerHTML;
const plus = document.querySelector(".plus");
const minus = document.querySelector(".minus");
const one = document.querySelector(".one");
const two = document.querySelector(".two");
const three = document.querySelector(".three");
const four = document.querySelector(".four");
const five = document.querySelector(".five");
const six = document.querySelector(".six");
const seven = document.querySelector(".seven");
const eight = document.querySelector(".eight");
const nine = document.querySelector(".nine");
const ac = document.querySelector(".ac");

function getInput(number){
    console.log("i am here");
    console.log(number.textContent);
    if (input === 0){
        input = number.textContent;
        document.getElementById("input").innerHTML = input;
    }
    else{
        input += number.textContent;
        document.getElementById("input").innerHTML = input;
    }
}

two.addEventListener("click",getInput(two));

ac.addEventListener("click",() =>{
   input = 0;
   console.log(input);
   document.getElementById("input").innerHTML = input;
})
plus.addEventListener("click",() => {
    console.log(plus.textContent);
    input += plus.textContent;
    document.getElementById("input").innerHTML= input;
});

one.addEventListener("click",()=>{
    if (input === 0) {
        input = one.textContent;
        document.getElementById("input").innerHTML=input;
    }
    else {
    input += one.textContent;
    document.getElementById("input").innerHTML=input;
    }
})

第二个问题,有没有更简单的方法通过不绑定每个键来检测用户的输入? (我是 JS 新手,这对我有很大帮助)

卡帕克

【问题讨论】:

  • click ... ,(e) => getInput(two)

标签: javascript calculator


【解决方案1】:

要在事件侦听器中触发带有参数的函数,您需要在事件侦听器中创建一个函数,该函数使用参数执行您的函数:

btn.addEventListener("click", () => { yourFunction(parameter) });

要统一事件绑定,您可以这样做:

const numberBtns = document.querySelectorAll(".number-btns");
numberBtns.forEach( btn => btn.addEventListener(....));

要获取您按下的数字,您可以使用数据集或参考按钮的值:

<button data-number="1" class="number-btns" value="1">
// JS:
btn.dataset.number // = 1
btn.value // = 1

【讨论】:

  • 谢谢你,它有效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多