我有一个现场点击活动,一个标题在打开时向上/向下翻转箭头.关闭它的内容.
最奇怪的事情正在发生!接着是一个变量 – 它应该从真实中翻转 – >是假的,反之亦然.基本上它根本不工作,它翻转到假并停留在那里……检查小提琴,看看我的意思.
$(document).on('click','.regimenHeader',function () { var _state = $(this).attr('data-state'); if (_state === 'true') { // do stuff } else { // do stuff } // This is where the issue is happening,it isn't flipping the Boolean value // !"true" = false,!true = false,it works with strings or booleans $(this).attr('data-state',!_state); });
如果我执行以下操作,我可以完美地工作:
if (_state === 'true') { // Manually flip the data-state boolean $(this).attr('data-state',false); }
有什么我错过了为什么这不应该按照应该的方式工作?只是想知道它为什么这样做!
解决方法
我想你是想这样做的:
如果是这样,问题是你使用.attr()返回一个字符串,所以如果你转换:
!"true" //false !"false" //false
另一方面,.data()返回已经“转换”的值
编辑:
为了更清楚,在javascript中唯一的假值是:
false; null; undefined; ''; 0; NaN;
所以,如果你真的想使用.attr(),你可以,但我建议你先做:
var _state = $(this).attr('data-state') === 'true'; //if 'true' then true,false otherwise
祝好运!