我不明白为什么这不起作用:
$(document).ready(function() {
if ($('.checkarea.unchecked').length) {
$(this).parent().parent().parent().parent().parent().parent().parent().removeClass('checked').addClass('unchecked');
}
else {
$(this).parent().parent().parent().parent().parent().parent().parent().removeClass('unchecked').addClass('checked');
}
});
这是 HTML 结构的屏幕截图:http://cloud.lukeabell.com/JV9N (已更新正确的屏幕截图)
此外,必须有一种更好的方法来查找项目的父项(页面上有多个这些元素,因此我需要它只影响未选中的元素)
以下是涉及的其他一些可能很重要的代码:
$('.toggle-open-area').click(function() {
if($(this).parent().parent().parent().parent().parent().parent().parent().hasClass('open')) {
$(this).parent().parent().parent().parent().parent().parent().parent().removeClass('open').addClass('closed');
}
else {
$(this).parent().parent().parent().parent().parent().parent().parent().removeClass('closed').addClass('open');
}
});
$('.checkarea').click(function() {
if($(this).hasClass('unchecked')) {
$(this).removeClass('unchecked').addClass('checked');
$(this).parent().parent().parent().parent().parent().parent().parent().removeClass('open').addClass('closed');
}
else {
$(this).removeClass('checked').addClass('unchecked');
$(this).parent().parent().parent().parent().parent().parent().parent().removeClass('closed').addClass('open');
}
});
(也非常愿意对该部分进行改进)
非常感谢!
这是发生这一切的链接:http://linkedin.guidemytech.com/sign-up-for-linkedin-step-2-set-up-linkedin-student/
<小时/>更新:
我已经根据评论改进了代码,但仍然存在第一部分无法正常工作的问题。
$(document).ready(function() {
if ($('.checkarea.unchecked').length) {
$(this).parents('.whole-step').removeClass('checked').addClass('unchecked');
}
else {
$(this).parents('.whole-step').removeClass('unchecked').addClass('checked');
}
});
--
$('.toggle-open-area').click(function() {
if($(this).parents('.whole-step').hasClass('open')) {
$(this).parents('.whole-step').removeClass('open').addClass('closed');
}
else {
$(this).parents('.whole-step').removeClass('closed').addClass('open');
}
});
$('.toggle-open-area').click(function() {
$(this).toggleClass('unchecked checked');
$(this).closest(selector).toggleClass('open closed');
});
$('.checkarea').click(function() {
if($(this).hasClass('unchecked')) {
$(this).removeClass('unchecked').addClass('checked');
$(this).parents('.whole-step').removeClass('open').addClass('closed');
}
else {
$(this).removeClass('checked').addClass('unchecked');
$(this).parents('.whole-step').removeClass('closed').addClass('open');
}
});
最佳答案
closest( selector )
Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
parents( [selector] )
Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
关于jquery - "find parent"和 if 语句的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12442644/