使用jQuery切换元素的属性?

Dea*_*anH 2 jquery attributes toggle wai-aria

使用jQuery构建树状菜单,我希望它可以访问,所以我使用的是aria属性.我想要做的是在点击/输入时将"aria-expanded"属性从true切换为false.我试过这个,但显然不正确:

$(this).closest('ul').find('> li.tree-parent').toggleAttr( 'aria-expanded', 'true false' );
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 12

您可以使用.attr()手动编写切换逻辑

$(this).closest('ul').find('> li.tree-parent').attr('aria-expanded', function (i, attr) {
    return attr == 'true' ? 'false' : 'true'
});
Run Code Online (Sandbox Code Playgroud)