如何在页面加载时不触发函数的情况下在事件监听器上传递参数? [重复]

我有一个要创建的三向切换,当用户单击选项时,我想显示他们选择了哪个选项(并移动选择器div来显示此内容)

因此,每个选择都有一个事件侦听器:

document.getElementById("option1").addEventListener("mouseover", UIController.changeSelection("option1"));
document.getElementById("option2").addEventListener("mouseover", UIController.changeSelection("option2"));
document.getElementById("option3").addEventListener("mouseover", UIController.changeSelection("option3"));

然后将调用changeSelection函数:

 changeSelection: (function(choice) {
        var option1 = document.getElementById("option1");
        var option2 = document.getElementById("option2");
        var option3 = document.getElementById("option3");
        var selector = document.getElementById("selector");
        if (choice === "option1") {
            selector.style.left = 0;
            selector.style.width = option1.clientWidth + "px";
            selector.style.backgroundColor = "#777777";
            selector.innerHTML = "Option 1";
        } else if (choice === "option2") {
            selector.style.left = option1.clientWidth + "px";
            selector.style.width = option2.clientWidth + "px";
            selector.innerHTML = "Option 2";
            selector.style.backgroundColor = "#418d92";
        } else {
            selector.style.left = option1.clientWidth + option2.clientWidth + 1 + "px";
            selector.style.width = option2.clientWidth + "px";
            selector.innerHTML = "Option 3";
            selector.style.backgroundColor = "#4d7ea9";
        }
    })

但是,通过将()添加到我的事件监听器中,它会立即触发该函数,然后此后将不再起作用。

使用EventListener时如何向函数传递参数?

谢谢你们!

评论
  • Lucy
    Lucy 回复

    您可以按以下方式添加函数定义:

    document.getElementById("option1")
            .addEventListener("mouseover", () => UIController.changeSelection("option1"));