I'm trying to have a click event where the user clicks a Div Question, then Jquery clones the Div Answer and displays it in a separate Div Clone.
Example here: http://jsfiddle.net/jessikwa/zNL63/2/
For some reason the following variable is coming back null. Any ideas?
var answer = $(this).parent().find(".faq-answer").clone();
Full code:
$(document).ready(function () {
var faqQuestion = $('.faq-question');
var faqClone = $('.faq-clone');
faqQuestion.click(function () {
showAnswer();
});
faqClone.click(function () {
hideAnswer();
});
function showAnswer() {
$(".faq-clone").hide("slide");
$('.faq-clone').html("");
var answer = $(this).parent().find(".faq-answer").clone();
$('.faq-clone').append(answer.html());
$(".faq-clone").show("slide");
}
function hideAnswer() {
$(".faq-clone").hide("slide");
$('.faq-clone').html("");
}
});
The easiest way to solve this would be to pass the handlers by reference:
faqQuestion.click(showAnswer);
faqClone.click(hideAnswer);
Now this
inside of showAnswer
and hideAnswer
will be the clicked element.
You can not access element by $(this) within a function. You would need to pass that as a parameter.
Try:
function showAnswer(passedObject) {
$(".faq-clone").hide("slide");
$('.faq-clone').html("");
var answer = passedObject.parent().find(".faq-answer").clone();
$('.faq-clone').append(answer.html());
$(".faq-clone").show("slide");
}
and then you would use that function: showAnswer($(this))
or more logical & cleaner solution is what @Kevin B suggested.
Make it even simplier, use next()
jQuery function
Is there any reason why you want to clone an hidden element and only show its clone ?
$(document).ready(function () {
var faqQuestion = $('.faq-question');
var faqClone = $('.faq-answer');
faqQuestion.click(showAnswer);
faqClone.click(hideAnswer);
function showAnswer() {
$(this).next('.faq-answer').show('slide');
}
function hideAnswer() {
$(this).hide("slide");
}
});
and apply to .faq-answer
the .faqClone
CSS
You could even produce short answer from a data-attribute :) to shorten even more HTML .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.