我有一些代码将函数作为事件传递。我想在单击按钮时调用该函数,但该函数需要一个参数。我可以通过写来传递参数, 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);