1

The one without callback function jsFiddle produces wrong outcome. The console log should show i=0 & j=0 as indicated "group[0] record[0]". because I am trying to find the dd/dt set: "Book: a book name".

I understand I need to include a callback function similar to this post. However I don't seem to understand how to insert the function correctly. Here is the one I am working on:

jsfiddle w/ callback

var arrDL = [];
$("dl").each(function(i) {     
   arrDL[i] = [];
   $(this).children("dt").each(function(j){ 
       function(n){
            return function(){
                var $this = $(this); 

                arrDL[n][j] = {
                   title: $this.text(),
                   description: $this.next("dd").text()
                };

                if($this.text() == "Book:" && $this.next("dd").text() == "another book name"){
                   console.log("group 0 record 0: " + n + '-' + j);
                };
           };    
      }(n);               
  });    
});

Thanks for your help.

Community
  • 1
  • 1
user1824996
  • 259
  • 1
  • 3
  • 14

1 Answers1

2

You are creating a function inside the function (inside the callback for the inner each) and returning it. You are executing the outer function, but it returns a function reference which you don't execute, so the code inside the inner function will never run.

Also you are sending the variable n into the outer function, but it's never defined anywhere, so it will just be undefined.

Actually there is no need for either the outer or the inner function, just put the code in the callback for the each:

var arrDL = [];
$("dl").each(function(i) {     
  arrDL[i] = [];
  $(this).children("dt").each(function(j){ 
    var $this = $(this);
    arrDL[i][j] = {
      title: $this.text(),
      description: $this.next("dd").text()
    };
    if($this.text() == "Book:" && $this.next("dd").text() == "another book name"){
      console.log("group 0 record 0: " + i + '-' + j);
    };
  });    
});

The result that you get is correct, the description "another book name" is found in the second group, not the first group.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • @user1824996: Yes, I arrived at the same code as in your fiddle when cleaning up the code in your question. :) – Guffa Feb 02 '13 at 08:22