如何在jquery中将属性值作为文本获取

use*_*214 0 jquery

当您单击菜单中的菜单项时,我正在尝试创建一个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');
    }
});
})
Run Code Online (Sandbox Code Playgroud)

Per*_*ark 5

display不是html-object的属性.您需要在下一行检查您使用css设置的值:

if($(this).children().css('display') == 'none') {   
    $(this).children().css('display', 'block');
}
Run Code Online (Sandbox Code Playgroud)

更好的是:

$(document).ready(function() {
    $("#left-help-menu li").click(function() {
        $(this).children().toggle();
    });
})
Run Code Online (Sandbox Code Playgroud)

编辑:相同的代码与注释和变量清晰

$(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();
    });
})
Run Code Online (Sandbox Code Playgroud)

注意:这实际上并没有使<li>"幻灯片" 的内容上/下.如果你想要,你可以使用该$.slideToggle()方法.