首页 > javascript > 如何在分配函数时将变量传递给DOM元素 - Javascript

如何在分配函数时将变量传递给DOM元素 - Javascript (How to pass a variable to DOM element when assigning a function - Javascript)

2019-03-07 javascript

问题

有没有一种简单的方法将函数和变量链接到DOM元素?

下面是一个如何工作的示例:

function logfunc(value){
  console.log(value)
}

document.getElementById('logger1').onclick = logfunc('this is button1')

document.getElementById('logger2').onclick = logfunc('this is button2')
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">


预期结果:

按下按钮,这是按钮x'。

解决方法

下面的代码段用于.addEventListener()在单击按钮时执行某些操作,并.value获取元素的值。这this是一个关键字,在这种情况下表示您单击的按钮。换句话说,由于您单击的按钮document.getElementById('logger1')在DOM中表示,您可以简单地this用来表示它。

此外,我不知道这是一个实际错误,还是一个错字,但你拼写functionfucntion。我在片段中为您修复了该错误。

最后,你用过了.onclick。这是有效的,并且是有效的代码,但它不是最好的方法。由于我不会涉及这个(这不是主要问题),你可能想到这里了解更多信息。

function logfunc(value) {
  console.log(value)
}

document.getElementById('logger1').addEventListener("click", function() {
  logfunc('this is ' + this.value);
});

document.getElementById('logger2').addEventListener("click", function() {
  logfunc('this is ' + this.value);
});
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">


问题

Is there an easy way to link both functions and variables to a DOM element?

Below is an example of how this might work:

function logfunc(value){
  console.log(value)
}

document.getElementById('logger1').onclick = logfunc('this is button1')

document.getElementById('logger2').onclick = logfunc('this is button2')
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">

Expected result:

'This is Button x' on button click.

解决方法

The snippet below uses .addEventListener() to do something when you click the button, and .value to get the value of the element. The this is a keyword that in this case means the button you clicked. In other words, since the button you clicked is represented by document.getElementById('logger1') in the DOM, you can simply use this to represent that.

Also I don't know if it was an actual error, or a typo, but you spelled function like fucntion. I fixed that error for you in the snippet.

And finally, you used .onclick. That works, and is valid code, but it isn't the best way to do it. Since I won't be going into this (this isn't the main question), you might want to go here to find out more.

function logfunc(value) {
  console.log(value)
}

document.getElementById('logger1').addEventListener("click", function() {
  logfunc('this is ' + this.value);
});

document.getElementById('logger2').addEventListener("click", function() {
  logfunc('this is ' + this.value);
});
<input type="button" id="logger1" value="Button 1">
<input type="button" id="logger2" value="Button 2">

相似信息