将参数传递给 onclick 函数

时间:2021-07-18 22:16:17

标签: javascript

在下面的代码中,我试图调用 answerButtonPressed 并在单击按钮时传递字符串 'left_button' 和 'right_button' 作为参数。照原样,我知道当我定义 answerLeftButtonFunction 时,它会立即获得 answerButtonPressed('left_button') 的值。我如何才能将对该函数的引用传递给 showButton,以确保在单击按钮时它调用 answerButtonPressed 同时将正确的字符串作为参数传递?

我能想到的唯一方法是使用全局变量或为我试图避免的每个按钮创建一个函数。

执行此操作的“正确”方法是什么?

const answerLeftButtonFunction = answerButtonPressed('left_button')
const answerRightButtonFunction = answerButtonPressed('right_button')
showButton(left_button, answer, answerLeftButtonFunction)
showButton(right_button, answer, answerRightButtonFunction)

function showButton(button, text, button_function) {
    button.innerText = text
    button.onclick = button_function
}

3 个答案:

答案 0 :(得分:1)

您可以在按钮上使用数据属性使它们“自我感知”,然后设置一个侦听器来测试 1) 单击的按钮是否是我们的左/右按钮之一,然后 2) 它是其中的哪个按钮.

window.addEventListener('load', () => {
  document.addEventListener('click', e => {
    if (e.target.classList.contains('btn-dir')) {
      // one of our buttons
      console.log(`The ${e.target.dataset.dir} button was clicked`);
    }
  })
})
<button class='btn-dir' data-dir="left">< Left</button>
<button class='btn-dir' data-dir="right">Right ></button>

答案 1 :(得分:0)

老实说,创建​​新函数是最好且“正确”的方法。与其他一些“脚本”语言不同,JavaScript 中的函数创建/调用并不像您想象的那么昂贵。 虽然重新阅读了您的问题,但似乎您的意思是复制 answerButtonPressed VS 为其创建匿名包装函数。

因此:

showButton(left_button, answer, () => answerButtonPressed('left_button'))

或者,由于 onclick 将使用 DOM event 调用您的处理程序,其中包含(除其他外)对被点击的对象(例如按钮)的引用,您可以使用它来确定按钮名称。您仍然必须能够访问按钮名称,例如将其存储为按钮对象上的 HTML 属性。

答案 2 :(得分:0)

你可以尝试类似的东西

const answerLeftButtonFunction = () => answerButtonPressed('left_button')
const answerRightButtonFunction = () => answerButtonPressed('right_button')
showButton(left_button, answer, answerLeftButtonFunction)
showButton(right_button, answer, answerRightButtonFunction)

function showButton(button, text, button_function) {
    button.innerText = text
    button.onclick = button_function
}
相关问题