[英](this).parent().find('.classname') not working
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. 我正在尝试一个单击事件,用户单击一个Div问题,然后Jquery克隆该Div Answer并将其显示在单独的Div Clone中。
Example here: http://jsfiddle.net/jessikwa/zNL63/2/ 此处的示例: 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. 现在,
this
里面showAnswer
和hideAnswer
将是点击的元素。
You can not access element by $(this) within a function. 您不能通过函数中的$(this)访问元素。 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))
然后您将使用该函数:
showAnswer($(this))
or more logical & cleaner solution is what @Kevin B suggested. @Kevin B建议使用更合理或更清洁的解决方案。
Make it even simplier, use next()
jQuery function 使它更简单,使用
next()
jQuery函数
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 并应用于
.faq-answer
.faqClone
CSS
You could even produce short answer from a data-attribute :) to shorten even more HTML . 您甚至可以从数据属性中得出简短答案:)以缩短更多HTML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.