Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is my 'this' not changing context inside inner jQuery each loop?
    text
    copied!<p>The idea is that I want to loop through these objects and build an HTML structure which will be added to the page. I thought it would be cleaner to do it all in the chain, but apparently I'm not understanding something about the context of <code>this</code> as it evolves through inner loops. I've looked a bit at <code>jQuery.proxy()</code> a bit, but I'm not sure I understand how to apply it here. Maybe there is another way altogether of doing what I'm trying to do here...</p> <pre><code>var obj = [ {"id":1213854620001,"name":"item 1","URL":"1213897576001.jpg"}, {"id":1213854619001,"name":"item 2","URL":"1213890384001.jpg"}, {"id":1213854618001,"name":"item 3","URL":"1213890378001.jpg"}, {"id":1213854616001,"name":"item 4","URL":"1213897663001.jpg"}, {"id":1213854615001,"name":"item 5","URL":"1213897554001.jpg"} ]; $(function() { if(obj.length) { $("&lt;ul/&gt;",{id:"myID"}).append(function(){ var that = document.createDocumentFragment(); $.each(obj,function(index,dataObj){ $("&lt;li/&gt;",{data:{dataID:dataObj.id},text:dataObj.name}) // this === obj[index] === dataObj, shouldn't it be the [object HTMLLIElement] .live("click",function(event) { openVideo($(event.target).data(dataID)); }) .append(function() { return $("&lt;img/&gt;",{src:dataObj.thumbnailURL})[0]; }) .appendTo(that); }); return that; }).appendTo("body"); } }); function openVideo(str) { //console.log(str); } </code></pre> <p>The implicit question becomes, why is <code>that</code> empty after my loop? and how can I build this HTML structure with nested loops?</p> <p>Using the suggestions from the comments, and answers, I built this, which seems to work exactly as it should, reads a little cleaner, and lets jQuery do all the javascript (e.g. <code>documentFragment</code> creation, and manipulation, etc):</p> <pre><code>$(function() { if(obj.length) { $("&lt;ul/&gt;",{id:"myID"}) .delegate("li","click",function(){openVideo($(this).data("dataID"));}) .append(function() { var that = $(this); $.each(obj,function(index,dataObj) { $("&lt;li/&gt;",{data:{dataID:dataObj.id},text:dataObj.name}).each(function() { $("&lt;img/&gt;",{src:dataObj.URL}).appendTo(this); that.append(this); }) }); }).appendTo("body"); } }); </code></pre>
 

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