我想要一个开闭功能。如果<div>
打开时,当我单击它时,它应该关闭,当我再次单击它时,它应该重新打开。 JSFiddle
HTML
<div class='answer'>answer</div>
<div style='display:none'>
<textarea name='talking'></textare>
<input type='submit'>
</div>
Jquery
$('.answer').click(function(){
if($(this).next().css('display','none')){
$(this).next().css('display','block');
}else if($(this).next().css('display','block')){
$(this).next().css('display','none');
}
})
在此示例中,“if”子句有效(它打开),但“else if”不起作用(它不会再次关闭)。
最佳答案
在条件语句中,您应该检索元素的 display
属性并将其与属性值的字符串进行比较。
所以说
if ( $(this).next().css('display', 'none') ) {
// ...
}
应该是:
if ( $(this).next().css('display') === 'none' ) {
// ...
}
$('.answer').click(function () {
if ($(this).next().css('display') === 'none') {
$(this).next().css('display', 'block');
} else if ($(this).next().css('display') === 'block') {
$(this).next().css('display', 'none');
}
});
不过,您的代码可以简化为以下内容:
$('.answer').on('click', function () {
$(this).next().toggle();
});
.toggle()
method处理所有这些逻辑。
关于javascript - else if 子句没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28776511/