如何判断div的ID值与localStorage值相等?对比返回false问题排查
问题原因及解决办法
你的代码里存在一个典型的类型匹配错误:
- 变量
parentEl已经是div的ID字符串(值为'test'),但你在判断条件里用$(parentEl)把它包装成了jQuery对象 localStorage.getItem('contentid')返回的是字符串类型的值- 对象和字符串用
==对比永远不会相等,哪怕内容看起来一致,这就是控制台打印值相同但判断返回false的核心原因
修正后的代码
<div id="test"></div> $('button').on('click', function(){ var parentEl = $('div').attr('id'); localStorage.setItem('contentid', 'test'); // 直接用parentEl字符串与localStorage的值对比 if(parentEl == localStorage.getItem('contentid')) { console.log('id === localstorage', parentEl == localStorage.getItem('contentid')); console.log('local', localStorage.getItem('contentid')); console.log('id', parentEl); console.log('can\'t go next'); } else { console.log('go next'); } });
另外注意你原代码里的console.log('can\t go next');存在转义错误,\t会被解析为制表符,应该改为can\'t来正确显示单引号,修正代码里已同步调整。
内容的提问来源于stack exchange,提问作者Neron Godfather
相关产品推荐
相关产品推荐

