jQuery点击按钮获取自定义属性值写入Cookie失败求助
问题根源
- 代码里的
$(this).val($(this).attr("accent-switcher"))是错误用法:.val()是用来设置元素的value属性的,它返回的是jQuery对象,不是我们需要的属性值,这就导致Cookie里存的不是预期的"blue"或"yellow",而是一个对象。 - 没必要用
each循环遍历绑定事件:jQuery选择器可以直接给所有匹配的元素绑定点击事件,手动遍历纯属多余。
修正后的代码
JavaScript代码
$(document).ready(function() { $("[accent-switcher]").click(function() { // 拿到当前按钮的accent-switcher属性值 const accentValue = $(this).attr("accent-switcher"); // 清除旧的Cookie ips.utils.cookie.unset('ipsTheme_type'); // 把属性值写入Cookie ips.utils.cookie.set('ipsTheme_type', accentValue, true); }); });
HTML代码(无需改动)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class='ipsButton' accent-switcher="blue">Color A</button> <button class='ipsButton' accent-switcher="yellow">Color B</button>
额外优化建议
如果是用来存储数据的自定义属性,推荐用HTML5标准的data-*属性,这样更规范。比如把属性改成data-accent-switcher="blue",然后用$(this).data('accentSwitcher')来获取值:
修改后的HTML:
<button class='ipsButton' data-accent-switcher="blue">Color A</button> <button class='ipsButton' data-accent-switcher="yellow">Color B</button>
对应的JS获取代码:
const accentValue = $(this).data('accentSwitcher');
内容的提问来源于stack exchange,提问作者Alexandru Miclea
相关产品推荐
相关产品推荐

