如何用jQuery实现点击段落切换内容的显示与隐藏?
问题修复方案
你的代码存在两个核心问题,导致无法实现点击切换显示/隐藏的效果:
每次点击都会重新获取当前HTML作为原始内容
第一次点击后,<p>的HTML已经变成了原文本+按钮,第二次点击时htmlorig会包含按钮,无法恢复到最初的纯文本状态。内部重复声明
toggle变量
在if/else块里用var toggle重新声明,导致外部的全局toggle变量从未被修改,每次判断时toggle始终是0,只会执行添加按钮的逻辑。
修复后的代码
<p class="test">test</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js" integrity="sha512-pumBsjNRGGqkPzKHndZMaAG+bir374sORyzM3uulLV14lN5LyykqNk8eEeUlUkB3U0M4FApyaHraT65ihJhDpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"> </script> <script> // 初始化toggle状态 let toggle = 0; // 提前保存原始HTML内容,避免每次点击重新获取 const originalHtml = $('p.test').html(); $('p.test').click(function() { if (toggle !== 1) { toggle = 1; $(this).html(originalHtml + '<button>sds</button>'); } else { toggle = 0; $(this).html(originalHtml); } }); </script>
优化思路(可选)
如果不想用全局变量,也可以用元素的data-*属性来存储状态,更符合模块化思维:
<p class="test">test</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js" integrity="sha512-pumBsjNRGGqkPzKHndZMaAG+bir374sORyzM3uulLV14lN5LyykqNk8eEeUlUkB3U0M4FApyaHraT65ihJhDpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"> </script> <script> // 提前保存原始内容到元素的data属性 $('p.test').data('originalHtml', $('p.test').html()); $('p.test').click(function() { const $this = $(this); // 从data属性获取状态,默认未激活 const isActive = $this.data('active') || false; if (!isActive) { $this.html($this.data('originalHtml') + '<button>sds</button>'); $this.data('active', true); } else { $this.html($this.data('originalHtml')); $this.data('active', false); } }); </script>
内容的提问来源于stack exchange,提问作者pire321
相关产品推荐
相关产品推荐

