当您单击菜单中的菜单项时,我正在尝试制作jquery slideUp / slideDown。我认为我可以通过基于display属性的值做一个条件来做到这一点,但由于某种原因它不起作用。我一定不能正确获取属性值,我做错了什么?
$(document).ready(function() {
$("#left-help-menu li").click(function() {
if($(this).children().attr('display') == 'none')
{
$(this).children().css('display', 'block');
}
else if($(this).children().attr('display') == 'block')
{
$(this).children().css('display', 'none');
}
});
})
答案 0 :(得分:5)
display
不是html-object的属性。您需要在下一行检查您使用css设置的值:
if($(this).children().css('display') == 'none') {
$(this).children().css('display', 'block');
}
更好的是:
$(document).ready(function() {
$("#left-help-menu li").click(function() {
$(this).children().toggle();
});
})
编辑:为了清晰起见,注释和变量的代码相同
$(document).ready(function() {
// When all the html has been loaded we locate all the <li> tags
var $lis = $("#left-help-menu li");
// After that we bind the click event on them to an anonymous function
$lis.click(function() {
// Whenever a <li> is clicked this code will run.
// First, lets get a hold of the clicked element
var $li = $(this);
// Now, find all the elements in that <li>
$children = $li.children();
// Lastly, lets hide or show them
$children.toggle();
});
})
注意:这实际上并不会使<li>
“幻灯片”的内容上/下。如果您愿意,可以使用$.slideToggle()
方法。
答案 1 :(得分:0)
display
是样式非属性。将.attr()
更改为.css()
试试这个,
$(document).ready(function() {
$("#left-help-menu li").click(function() {
if($(this).children().css('display') == 'none')
{
$(this).children().css('display', 'block');
}
else if($(this).children().css('display') == 'block')
{
$(this).children().css('display', 'none');
}
});
})