简体   繁体   中英

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 . All is working fine but I can't capture the id or value of the button that is eventually clicked.

When I define btn.onclick=gold_2(value) to export variable value the function executes link I have already clicked the button. when I define btn.onclick=gold_2 I can't capture the button id/value that I click.

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

The problem is that you are using comma operator b/w gold_2 and "value" . The whole expression will evaluate to the last expression ie "value" .

I would suggest you using eventListeners rather than directly changing the function

btn.addEventListener('click',gold_2);

Second problem is that id is undefined inside gold_2 . You can use this to access the element

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. this in gold_2 will be the element clicked so you can access its value.

Using Wrapper function to pass variable

If you still want to pass value variable to gold_2 you can use wrapper function. Also remove '' around value

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

You will then also need to accept a variable inside function gold_2

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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