如何用jQuery实现单击事件双向切换元素ID属性值?
问题分析与修正方案
你的代码存在几个关键问题,导致仅第一次点击生效:
- ID判断逻辑错误:
attr('id')获取的是元素ID的纯文本值(不带#),但你判断时错误地添加了#;且第一次修改时给ID值也加了#,导致后续判断完全不匹配。 - 条件重复冗余:两个
else if的判断条件完全一致,逻辑上永远不会触发第二个分支。 - 无效变量定义:
$thisVideoWrap的写法毫无意义,$(this)已经是当前点击的.videoWrap元素,不需要再用find去查找自身。 - 拼写/大小写不一致:需求里写的是
cardvieo_localstream,代码里用的是cardvideo_localStream,字符和大小写差异会直接导致判断失效。
修正后的代码
$('.video-list .videoWrap').on('click', function() { // 定义要切换的两个ID,统一拼写避免错误 const localStreamId = 'cardvideo_localstream'; const remoteStreamId = 'cardvideo_remotestream'; const currentId = $(this).attr('id'); // 判断当前ID并切换 if (currentId === localStreamId) { $(this).attr('id', remoteStreamId); } else if (currentId === remoteStreamId) { $(this).attr('id', localStreamId); } });
代码说明
- 先定义两个常量存储要切换的ID,避免拼写或大小写错误。
- 获取当前元素的ID值(纯文本,不带
#),直接判断并切换为对应的另一个ID。 - 移除了无用的变量定义,简化逻辑。
如果你的需求里确实需要同时修改$mainVideoWrap的ID,可以调整代码如下:
$('.video-list .videoWrap').on('click', function() { const $this = $(this); const $mainVideoWrap = $('.mainVideoWrap'); const localStreamId = 'cardvideo_localstream'; const remoteStreamId = 'cardvideo_remotestream'; const currentId = $this.attr('id'); if (currentId === localStreamId) { $this.attr('id', remoteStreamId); $mainVideoWrap.attr('id', localStreamId); } else if (currentId === remoteStreamId) { $this.attr('id', localStreamId); $mainVideoWrap.attr('id', remoteStreamId); } });
内容的提问来源于stack exchange,提问作者R sukumar
相关产品推荐
相关产品推荐

