jQuery判断data属性为true时如何给指定ID按钮添加类
实现方案
代码不生效主要有两个核心原因:
- 选择器引号嵌套错误:之前编写的属性选择器外层用双引号包裹,内部匹配属性值
true时也使用双引号,会把外层字符串提前截断,导致选择器无法正确解析目标元素。 - 语法结构错误:在jQuery选择器语句后直接跟独立大括号代码块的写法,不符合JS语法规范,浏览器执行时会直接抛出语法错误,块内的按钮类添加逻辑根本不会被触发。
静态场景适配
如果只需要在页面加载时判断一次#first-slide的data-isactiveslide属性值,满足为true的条件就给#my-button添加underline类,直接使用如下代码即可:
// 修正引号嵌套的选择器,判断匹配元素是否存在 if (jQuery('#first-slide[data-isactiveslide="true"]').length) { jQuery('#my-button').addClass('underline'); }
动态状态联动适配
如果是轮播类组件,#first-slide的data-isactiveslide值会随页面交互动态变化,需要类名跟着同步增减,可以使用原生属性监听实现自动联动:
const $firstSlide = jQuery('#first-slide'); // 监听目标元素的属性变化,根据激活状态切换按钮类名 new MutationObserver(() => { const isActive = $firstSlide.attr('data-isactiveslide') === 'true'; jQuery('#my-button').toggleClass('underline', isActive); }).observe($firstSlide[0], { attributes: true, attributeFilter: ['data-isactiveslide'] });
内容的提问来源于stack exchange,提问作者Skt
相关产品推荐
相关产品推荐

