使用jQuery切换元素的属性? [英] Toggle an element's attribute with jQuery?

查看:92
本文介绍了使用jQuery切换元素的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery构建树形菜单,并且希望它可访问,因此我使用aria属性.我想做的是在单击/输入时将"aria-expanded"属性从true切换为false.我已经尝试过了,但这显然是不正确的:

Building a tree menu with jQuery, and I want it to be accessible, so I'm using aria attributes. What I want to do is toggle the "aria-expanded" attribute from true to false on click/enter. I've tried this, but it's obviously not correct:

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

推荐答案

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

You can use .attr() to manually write the toggle logic

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

这篇关于使用jQuery切换元素的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆