简体   繁体   English

如何通过onclick事件发送变量?

[英]How to send a variable through a onclick event?

I have created an array. 我创建了一个数组。 this array creates buttons with specific and commons attributes. 此数组创建具有特定和公共属性的按钮。 after appending them to div(id=form2) I give them an on click function gold_2 . 将它们附加到div(id=form2)我给它们点击功能gold_2 All is working fine but I can't capture the id or value of the button that is eventually clicked. 一切正常,但我无法捕获最终点击的按钮的ID或值。

When I define btn.onclick=gold_2(value) to export variable value the function executes link I have already clicked the button. 当我定义btn.onclick=gold_2(value)来导出变量值时,函数执行链接我已经点击了按钮。 when I define btn.onclick=gold_2 I can't capture the button id/value that I click. 当我定义btn.onclick=gold_2我无法捕获我点击的按钮ID /值

var gold_item = ['CL', 'LR', 'GR', 'TP', 'JH', 'CH', 'HR', 'CK', 'BA', 'BL', 'CP', 'MG', 'XY', 'SC', 'BC', 'PS', 'MS', 'KL', 'DM', 'NP', 'PN', 'DN', 'GC', 'RG', 'CD'];

for (var i = 0; i < gold_item.length; i++) {
  var btn = document.createElement("BUTTON");
  //btn.innerHTML=goldItem[i];
  btn.className = "form2_button";
  btn.id = gold_item[i];
  btn.value = gold_item[i];
  btn.innerHTML = gold_item[i];
  var value = gold_item[i];
  document.getElementById('form2').appendChild(btn);
  btn.onclick = gold_2, 'value';
}

function gold_2() {
  var val = document.getElementById(id).value
  alert(val);
}

Using this and addEventListener without passing value 使用thisaddEventListener而不传递value

The problem is that you are using comma operator b/w gold_2 and "value" . 问题是你使用逗号运算符b / w gold_2"value" The whole expression will evaluate to the last expression ie "value" . 整个表达式将评估到最后一个表达式,即"value"

I would suggest you using eventListeners rather than directly changing the function 我建议你使用eventListeners而不是直接更改函数

btn.addEventListener('click',gold_2);

Second problem is that id is undefined inside gold_2 . 第二个问题是在gold_2id undefined You can use this to access the element 您可以使用this来访问该元素

function gold_2() {
  var val = this.value
  alert(val);
}

As you are setting the value as the value of element so you don't need to pass it as argument. 当您将value设置为元素的值时,您不需要将其作为参数传递。 this in gold_2 will be the element clicked so you can access its value. thisgold_2将是一个点击的元素,所以你可以访问它的价值。

Using Wrapper function to pass variable 使用Wrapper函数传递变量

If you still want to pass value variable to gold_2 you can use wrapper function. 如果您仍想将value变量传递给gold_2 ,则可以使用包装函数。 Also remove '' around value 同时删除'' value

btn.onclick = () => gold_2(value);

You will then also need to accept a variable inside function gold_2 然后,您还需要接受函数gold_2的变量

function gold_2(val) {
  alert(val);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM