使用jQuery通过data属性切换CSS属性仅生效一次问题求助
问题根因
- jQuery的
data()方法读取自定义data属性时会做本地缓存,首次读取data-new-color的值后,后续调用data('new-color')默认会直接返回缓存值,不会同步DOM上你用attr()更新后的属性值,读写方法不统一导致取值一直是初始值,无法完成后续交换。 - 额外小问题:事件回调参数定义是
e,调用event.preventDefault()在部分严格环境下会报错,建议统一用传入的事件对象。
修复方案
你可以选择任意一种统一读写的方案解决问题:
方案1:统一用attr()读写data属性(会同步更新DOM上的属性值)
<span class="button" title="Switch background color"></span> <div class="targeted-element" style="background-color: #dedede;" data-new-color="rgba(14,22,33,1)"></div> <script> $('span.button').on('click', function(e) { e.preventDefault(); $('.targeted-element').each(function() { const $el = $(this); const currentBg = $el.css('background-color'); // 统一用attr读取,不走jQuery缓存 const switchBg = $el.attr('data-new-color'); $el.css('background-color', switchBg); $el.attr('data-new-color', currentBg); }); }); </script>
方案2:统一用data()读写(仅更新jQuery缓存,性能更好,不修改DOM原始属性)
$('span.button').on('click', function(e) { e.preventDefault(); $('.targeted-element').each(function() { const $el = $(this); const currentBg = $el.css('background-color'); const switchBg = $el.data('new-color'); $el.css('background-color', switchBg); // 用data更新缓存,而不是attr修改DOM $el.data('new-color', currentBg); }); });
两种方案按需选择即可,如果你的其他逻辑需要直接读取DOM标签上的
data-new-color属性,选方案1;没有这类需求选方案2即可。
内容的提问来源于stack exchange,提问作者oneone
相关产品推荐
相关产品推荐

