0

sorry for the title but I'm not sure what the correct terminology is for this issue. I am trying to dynamically generate a table of clickable elements using for loops in JavaScript. Each of the elements, when clicked, should trigger the same function but with different parameters. In my code I am setting the onClick function up like so:

elementArray[i].onClick = function() { clickFunction(i) };

However, when I do this the clickFunction is just taking whatever value i is currently set to, not what it was when I set the onClick function, which is what I want. Any ideas?

2 Answers2

1

As I got your question you want a table having clickable element calling to same function with diff param. [Let me know if it's not your question]

So taking i (index or row no.) would be param to that function.

HTML :

<table id='myTable'></table>

Javascript :

for(i = 9; i >= 0; i--) {
var table = document.getElementById("myTable");

// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);

// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell = row.insertCell(0);

// Add some text to the new cells:
cell.innerHTML = "<input type='button' onclick='callIt("+i+")'";
}
function callIt(index) {
alert(index);
}

I am considering that you want button to click. Hope it will help you.

more you can get on w3schools

0

Here's a version of @Bhojendra Nepal's "duplicate question" applied to your question. With this HTML:

<div class="element-0">0</div>
<div class="element-1">1</div>
<div class="element-2">2</div>

And this script:

var elementArray = [];
var creatFunc = function($this,i){
  return function() { 
    console.log(i);
    $this.html(i + 1);
    if (i>1) i++;
  };
};

for (var i = 0; i < 3; i++) {
  elementArray[i] = $('.element-' + i);
  elementArray[i].click( creatFunc( elementArray[i] , i) );
}

by creating the functions in a separate function, we've isolated the variable. I added "if (i>1) i++;" to show how the new function keeps its own variable and can increment it (keep clicking on the third div to see the number keep increasing).

here's a jsfiddle:

https://jsfiddle.net/mckinleymedia/1cksb8ky/

I hope this helps.

Oh, I added jQuery to this. I'm not positive how to get this working in vanilla javascript off hand.