我想要一个open-close函数。如果<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”不起作用了(它不再关闭)。
发布于 2015-02-28 08:18:40
在条件语句中,您应该检索元素的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处理所有这些逻辑。
https://stackoverflow.com/questions/28776511
复制相似问题