如何通过按钮OnClick功能实现文本Toggle切换?现有代码报错如何调整
原代码失效核心问题
- 逻辑与需求错位:需求要求
data-count-type="0"时,按钮显示data-charactercount的内容,原代码对应分支错误取了data-wordcount的值 - 漏写赋值动作:三元表达式的另一分支仅获取了
data-charactercount属性值、修改了data-count-type标记位,没有把获取到的文本赋值给按钮的innerText,文本自然不会更新 - 结构冗余混乱:把多条独立执行的语句压缩在三元表达式分支内用逗号分隔,没有明确每个分支的赋值逻辑,容易出现执行顺序错乱
可正常运行的修正方案
方案1:保留原内联点击的写法,拆分逻辑结构
摒弃硬压缩的三元写法,用清晰的分支判断实现效果,不需要额外依赖即可运行:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button type="button" data-count-type="0" data-wordcount="15 Words" data-charactercount="50 Character" onclick=" const currentType = this.getAttribute('data-count-type'); if(currentType === '0') { this.innerText = this.getAttribute('data-charactercount'); this.setAttribute('data-count-type', '1'); } else { this.innerText = this.getAttribute('data-wordcount'); this.setAttribute('data-count-type', '0'); } " > BUTTON </button>
方案2:配合引入的jQuery做更易维护的事件绑定
把内联点击逻辑抽离出来,代码可读性更高:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button type="button" data-count-type="0" data-wordcount="15 Words" data-charactercount="50 Character" > BUTTON </button> <script> $(function() { $('button[data-count-type]').on('click', function() { const $btn = $(this); const currentType = $btn.data('count-type'); if(currentType === 0) { $btn.text($btn.data('charactercount')).data('count-type', 1); } else { $btn.text($btn.data('wordcount')).data('count-type', 0); } }) }) </script>
提示:原生DOM的
getAttribute方法获取data-*属性时返回值为字符串类型,jQuery的.data()方法会自动将可转换的字符串转为数字类型,判断时注意类型匹配,避免隐式转换引发的判断错误。
内容的提问来源于stack exchange,提问作者Morgan Codes
相关产品推荐
相关产品推荐

