0

当您单击菜单中的菜单项时,我正在尝试制作 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');
    }
});
})
4

2 回答 2

5

display不是 html 对象的属性。您需要在下一行检查您使用 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()方法。

于 2012-11-02T13:36:25.823 回答
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');
    }
  });
})
于 2012-11-02T13:36:45.607 回答