Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd write it this way</p> <pre><code> for (i= 0; i&lt;reqs.length; i++) { var requestID = "request"+i; // Build the DIV for each request element.innerHTML += "&lt;div id="+requestID+" class=request&gt;&lt;img class=requestImage src=images/" +reqs[i].image+" alt=Face /&gt;&amp;nbsp;&amp;nbsp;"+reqs[i].name+"&lt;/div&gt;"; }// end for var requestElement = $(".request"); requestElement.hover( function() { $(this).removeClass().addClass("requestHover"); }, function() { $(this).removeClass().addClass("request"); } ); requestElement.click( // if the request is clicked, then alert me - testing function() { alert('Handler for .click() called.'); } ); </code></pre> <p>Edit to answer to your comment:</p> <p>No, it's a matter of closure. At the end of the loop, <code>requestID</code> is always the same, so <code>$("#"+requestID);</code> is always the same. It's has if there is only one bind. </p> <p>To overcome such a thing, you have some option:</p> <ul> <li>using $.each to loop (see <a href="http://forum.jquery.com/topic/binding-event-to-element-dynamically" rel="nofollow">http://forum.jquery.com/topic/binding-event-to-element-dynamically</a> , <a href="http://forum.jquery.com/topic/binding-click-event-in-a-loop" rel="nofollow">http://forum.jquery.com/topic/binding-click-event-in-a-loop</a>, <a href="http://api.jquery.com/jQuery.each/" rel="nofollow">http://api.jquery.com/jQuery.each/</a> )</li> <li>using the <code>live()</code> method (see <a href="http://api.jquery.com/live/" rel="nofollow">http://api.jquery.com/live/</a>, <a href="http://jsfiddle.net/VrzUb/1/" rel="nofollow">http://jsfiddle.net/VrzUb/1/</a> (used for the click))</li> <li>assigning the events thanks to a selector common to each object (e.g. using classes, as above)</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload