jQuery中检测按钮是否含指定属性的代码失效问题
问题场景
现有HTML结构:
<body> <button class="test" aria-label="This is a button"> <span>test</span> </button> <button class="test2" aria-label="This is a second button"> <span>test2</span> </button> </body>
需求:给所有父按钮带有aria-label属性的<span>元素添加aria-hidden="true"属性。
原代码问题分析
你尝试的几种写法都没生效,核心问题有三个:
$("button").attr("aria-label")仅会检查第一个匹配的按钮是否存在该属性,不会遍历所有按钮- if语句中的
this指向的是document(ready回调的上下文),不是目标按钮,因此无法找到对应内部的span getAttribute是原生DOM元素的方法,不能直接调用在jQuery对象上,jQuery对象需使用.attr()方法
正确实现方式
方法一:直接用属性选择器(推荐)
利用jQuery的属性选择器直接定位目标元素,一步完成操作:
jQuery(document).ready(function($) { // 选中所有带有aria-label属性的按钮内部的span,添加aria-hidden属性 $('button[aria-label] span').attr('aria-hidden', 'true'); });
方法二:遍历按钮逐个处理
如果需要更灵活的逻辑(比如额外判断属性值),可以用.each()遍历所有按钮:
jQuery(document).ready(function($) { $("button").each(function() { // 此处的this指向当前遍历的按钮DOM元素 if ($(this).attr("aria-label")) { $(this).find("span").attr("aria-hidden", "true"); } }); });
说明
- 方法一效率更高,适合简单的选择场景
- 方法二更灵活,可在遍历过程中添加额外的判断逻辑(比如检查
aria-label的具体值)
内容的提问来源于stack exchange,提问作者mikser io
相关产品推荐
相关产品推荐

