在Javascript中切换bool值 [英] switching bool values in Javascript

查看:68
本文介绍了在Javascript中切换bool值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个奇怪的问题:我有一个HTML属性,它只会是true或false,我用Jquery提取了它并将其转换为布尔值,然后我将其切换为相反的值(true到false,false到true) ,然后使用新的布尔值更改相同的HTML属性.

This is a weird issue: I have a HTML attribute that will only be true or false, i fetch it with Jquery and turn it into a boolean, then i switch it for the opposite (true to false, false to true), then i change the same HTML attribute with the new boolean value.

首先,当原始attr值为false并将其设置为true时,它开始工作,但反之则不行:

It works at first, when the original attr value is false and it get set to true, but not the other way around:

<button aria-checked="false" class="toggle-search" type="button">
    Toggle button is <span>false</span>
</button>

现在是Js/Jquery

And now the Js/Jquery

$(".toggle-search").click(function(){      

    var status = !$(this).attr("aria-checked"); 
    // returns string, turn to bool

    $(this).attr("aria-checked",!status);
    $(this).children("span").html(!status);

});

https://jsfiddle.net/kaqyhc48/4/

我不明白逻辑的含义,是不是将新值解析为false还是先解析为false,然后解析为true?

I dont understand what's going on with the logic, is the new value not being parsed to false or maybe being parsed to false first and then to true?

感谢您的帮助

推荐答案

您必须将字符串解析为布尔值.最简单的方法是value == "true",当字符串为"true"时返回true,否则返回false.

You have to parse the string to a boolean value. The simplest way to do it is value == "true", which returns true, when the string is "true" and false otherwise.

要将其解析回字符串,可以使用value ? "true" : "false".

To parse it back to a string you can use value ? "true" : "false".

$(".toggle-search").click(function() {

  var status = $(this).attr("aria-checked") == "true";
  status = !status;
  // returns string, turn to bool

  $(this).attr("aria-checked", status);
  $(this).children("span").html(status ? "true" : "false");

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button aria-checked="false" class="toggle-search" type="button">
    Toggle button is <span>false</span>
</button>

这篇关于在Javascript中切换bool值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆