检测html存在data-dyslexic-applied属性时移除指定span的style属性,JS不生效如何解决
问题排查
你的代码不生效有两个核心原因:
- 逻辑判断反向:你需要在
data-dyslexic-applied="true"存在时执行操作,但代码加了!取反,只有属性不存在时才会触发移除逻辑,自然无效果。 - 属性值判断逻辑不严谨:
attr()方法返回的是字符串类型的属性值,即使去掉取反符,若后续属性被设置为字符串"false",也会被判定为真值触发逻辑,存在隐患。
修复后的代码(jQuery版本)
如果需要同时校验属性存在且值为true:
if ($('html').attr('data-dyslexic-applied') === 'true') { $('span.material-icons').removeAttr('style'); }
如果仅需要判断属性是否存在,不需要校验值:
if ($('html').is('[data-dyslexic-applied]')) { $('span.material-icons').removeAttr('style'); }
检测元素指定属性的最优方案
- 原生JS场景:优先使用DOM内置的
hasAttribute()方法,性能最优、语义最明确
const htmlEl = document.documentElement // 仅判断属性是否存在 if (htmlEl.hasAttribute('data-dyslexic-applied')) { // 需判断属性值时追加判断 if (htmlEl.getAttribute('data-dyslexic-applied') === 'true') { document.querySelectorAll('span.material-icons').forEach(el => { el.removeAttribute('style') }) } }
- 针对
data-*格式的自定义属性,可使用更便捷的datasetAPI:
if (document.documentElement.dataset.dyslexicApplied === 'true') { // 执行对应逻辑 }
- jQuery场景:优先使用
$('选择器').is('[属性名]')判断属性是否存在,不要通过attr()返回值是否为undefined的方式判断,前者容错性更高。
内容的提问来源于stack exchange,提问作者Ivan Nukli
相关产品推荐
相关产品推荐

