【发布时间】: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);
【问题讨论】:
-
旁注:您应该在
document.body中插入内容,而不是在根<html>中
标签: javascript function parameter-passing function-invocation