javascript - Pass additional parameters to jQuery each() callback -


i'm working on app present surveys user. markup looks this:

<body>     <div class="question" id="q1">         question 1     </div>     <div class="question" id="q2">         question 2     </div>     <!-- etc --> </body> 

i want construct javascript objects dom using jquery, in survey constructor i'm traversing jquery set using each() method. problem within callback function i'm unable reference survey object in order append each question object survey.questions array. how can reference survey object? there way pass additional parameter (e.g. reference survey object) callback function?

function survey() {     this.questions = new array;     $('.question').each(function(i) { (/* survey object */).questions.push(new question(this)); }); }  function question(element) {     this.element = $(element); } 

you should able create reference survey before iterate on questions.

function survey() {     this.questions = new array();     var survey = this;     $('.question').each(function(i) {         survey.questions.push(new question(this));     }); }  function question(element) {     this.element = $(element); }  var survey = new survey();  $.each(survey.questions, function() {     $("ul").append("<li>" + this.element.text() + "</li>"); }); 

working example on jsfiddle


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -