【问题标题】:Is it possible to pass parameters to a function reference in JavaScript [duplicate]是否可以将参数传递给 JavaScript 中的函数引用 [重复]
【发布时间】:2022-01-05 12:50:21
【问题描述】:

我有一些代码将函数作为事件传递。我想在单击按钮时调用该函数,但该函数需要一个参数。我可以通过编写btn.addEventListener('click', displayMessage('Test'); 来传递参数,但该函数会立即被调用。我只想在单击按钮时调用该函数。是否可以在不立即调用函数的情况下传递参数?

function displayMessage(messageText) {
        const html = document.querySelector('html');

        const panel = document.createElement('div');
        panel.setAttribute('class','msgBox');
        html.appendChild(panel);

        const msg = document.createElement('p');
        msg.textContent = messageText;
        panel.appendChild(msg);

        const closeBtn = document.createElement('button');
        closeBtn.textContent = 'x';
        panel.appendChild(closeBtn);

        closeBtn.addEventListener('click', () => panel.parentNode.removeChild(panel));
}

const btn = document.querySelector('button');
/* To avoid calling the function immediately, I do not use the function invocation
 * operator. This prevents me from passing parameters, however.
 */
btn.addEventListener('click', displayMessage); 

【问题讨论】:

标签: javascript function parameter-passing function-invocation


【解决方案1】:

将其作为回调运行。

btn.addEventListener('click', () => displayMessage('text')); 

这样只会在点击事件运行时执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-21
    • 2012-11-13
    • 2015-05-11
    • 2021-07-29
    • 2013-07-09
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多