2 Questions, firstly I have this code:
function Question(container, question_list, chosenAnswer) {
this.container = container.empty();
this.question_list = question_list;
if(question_list.length == 1) {
container.append('<div class="answer">' + question_list[0] + '</div>');
} else if (question_list.length == 2) {
for(var i=0;i<question_list.length;i++){
container.append('<div class="two_q'+(i+1)+'">' + question_list[i] + '</div>');
}
addClickOn(container, chosenAnswer);
} else {
for(var i=0;i<question_list.length;i++){
container.append('<div class="four_q'+(i+1)+'">' + question_list[i] + '</div>');
}
addClickOn(container, chosenAnswer);
}
}
function addClickOn(container, chosenAnswer)
{
this.container = container;
$(container.children()).on('click', function() {
selected = $(this);
chosenAnswer= $(this).index();
selected.siblings().fadeOut();
selected.animate({
width: container.width(),
height: container.height()
});
selected.fadeOut();
});
}
var question_list1 = ["Question 1", "Question 2", "Question 3", "Question 4"];
var question_list2 = ["Statement1", "Statement2"];
var answer = ["Answer"];
var chosenAnswer;
new Question($('div.question_container'), question_list2);
console.log(chosenAnswer);
-
Why is chosenAnswer undefined on the console log? I haven’t defined it, but I have passed it through the functions till it gets set on the click event.
-
When one of the boxes is clicked and the animation has finished, I then want to return this chosenAnswer and repeat the Question function with a new array. How do I do this?
Thanks,
Rick
JavaScript is a call by value language. You can’t modify the value of a variable in the calling context like you can with a C++
&fooreference parameter.If you made “chosenAnswer” an object, then the function could use the reference to that object passed in as a parameter to modify the object contents. It’s hard to say exactly how to fix your code because it’s so unidiomatic.
Your use of
thisin “addClickOn()” is incorrect also. Again, it’s hard to say what the code should do instead, butthisin that function won’t refer to anything useful because of the way the function is called.