Javascript jQuery.click()未按预期触发
我想要实现的是:Javascript jQuery.click()未按预期触发,javascript,jquery,Javascript,Jquery,我想要实现的是: 用户第二次单击h4元素时,.question div应返回到35px高度,段落应将页边顶部设置为35px,从而使子段落滑入视图。当用户第二次单击h4元素时,.question div应返回到35px高度,段落应将页边顶部设置为35px。 jQuery(document).ready(function($) { $('.question h4').click(function () { $(this).parents('.question').css('
- 用户第二次单击h4元素时,.question div应返回到35px高度,段落应将页边顶部设置为35px,从而使子段落滑入视图。
- 当用户第二次单击h4元素时,.question div应返回到35px高度,段落应将页边顶部设置为35px。
jQuery(document).ready(function($) {
$('.question h4').click(function () {
$(this).parents('.question').css('height', '90');
$(this).siblings('p').css('margin-top', '0');
$(this).parent().addClass('open');
});
$('.question.open h4').click(function () {
$(this).parent.removeClass('open');
$(this).parents('.question').css('height', '65px');
$(this).siblings('p').css('margin-top', '35px');
});
});
即使
.question
是.open
,您的第一次单击处理程序也会启动。您需要从第一个选择器中排除。打开
$('.question:not(.open) h4').click(...
您实际上只需要一个处理程序:
$('.question h4').click(function () {
if ($(this).is('.open h4')) {
$(this).parent.removeClass('open');
$(this).parents('.question').css('height', '65px');
$(this).siblings('p').css('margin-top', '35px');
}
else {
$(this).parents('.question').css('height', '90');
$(this).siblings('p').css('margin-top', '0');
$(this).parent().addClass('open');
}
});
您的第二个处理程序分配没有任何作用,因为您的
元素都不是以“open”类开头的(或者,至少我怀疑它们不是)。正如Pointy提到的,您只需要一个带有条件语句的处理程序。另外,对于速度、开销和简单性,我会考虑将所有期望的动作串在一个节点上(即,您想用$$(this)来做任何事情。PARTENTHER()应该被串在一起,所以jQuery只需要解析DOM一次)。
打字错误<代码>$(此).parent
??此外,选中此项将有助于链接所有这些方法。首次单击事件将始终应用于这两种情况!使用一个处理程序并检查状态!这个答案是不正确的。“.open”处理程序如何处理所有没有“.open”类的
元素?这些都没有意义。您需要绑定到所有元素,然后检查它们是否有类……或者使用事件委派,但这确实是不必要的。保持OP的操作方式,绑定到两个不同的选择器(即使您“修复”了选择器),也不会奏效。我不知道我是怎么错过的。。。谢谢既然你指出了它为什么没有发射,我就把这个标记为答案。@mchandleraz好的,我刚刚对.is()
测试做了一个小的修改。这是我知道我做错了一段时间的事情,但我没有费心找出正确的方法。谢谢你的信息。我将很快重新编写我的jQuery:)
$('.question h4').click(function () {
if (!$(this).parent().hasClass('open')){
$(this).parents('.question').css('height', '90').addClass('open');
$(this).siblings('p').css('margin-top','0');
}else{
//$(this).parents('.question').css('height', '65px');
$(this).parent().css('height', '65px').removeClass('open');
$(this).siblings('p').css('margin-top', '35px');
}
});