0

I would like to create list of divs, one of the divs should like this:

<div onclick="myFunc(this, 'arrayValue')"></div>

I want to achieve it by iterating through my array and passing index value to my function. One of the solutions that worked was using setAttribute :

  for(var i = 0; i < array.length; i++){
    var div = document.createElement("div");
    div.setAttribute("onclick", 'myFunc(this, \''+array[i]+'\')');
    myDiv.appendChild(div);
  }

The only problem is that this part looks really ugly: \''+array[i]+'\')' Is there other way to achieve this? That would look like this or something similar:

    div.setAttribute("onclick", myFunc(this, array[i]);

btw. other solutions: when I used div.onclick the onclick attr was not visible on div (result: <div></div>), possibly I did something wrong.

priya_singh
  • 2,478
  • 1
  • 14
  • 32
zombie_ghast
  • 1,713
  • 15
  • 21
  • Possible duplicate of [onClick event in a For loop](http://stackoverflow.com/questions/15860683/onclick-event-in-a-for-loop) – Greg Burghardt Oct 03 '16 at 12:56
  • The *"...this part looks really ugly"* part makes this a better fit for Code Review. –  Oct 03 '16 at 12:59
  • The *"other solutions"* part would be on topic if you showed what you actually did and described what was wrong and what you mean by *"...attr was not visible"*. However, it would almost definitely be a duplicate. –  Oct 03 '16 at 13:00
  • https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener – Quentin Oct 03 '16 at 13:00
  • @squint Attr was not visible == `
    `, on the other hand attr visible == `
    ` <- version I want to achieve
    – zombie_ghast Oct 03 '16 at 13:44
  • Why do you want it to be visible, and where? What difference does that make to you? –  Oct 03 '16 at 13:49
  • It is not that I really need to to do this this way. I am just curious. The difference: without onclick attr it won't trigger a function. – zombie_ghast Oct 03 '16 at 13:55

1 Answers1

1

var array = ['bla1','bla2'];

var myFunc = function(value) {
  alert('click : '+ value);
};

var myDiv = document.getElementById('myDiv');

for(var i = 0; i < array.length; i++){
    var div = document.createElement("div");
    div.className = 'bla';
    myDiv.appendChild(div);
  
  div.addEventListener('click', myFunc.bind(this, array[i]));
}
.bla {
  border: 1px solid black;
  width: 20px;
  height: 20px;
  margin: 10px;
  }
<div id="myDiv"></div>

Is that you want ?

Steeve Pitis
  • 4,283
  • 1
  • 21
  • 24