javascript if - else 快捷方式不起作用?

发布于 2024-09-10 17:30:44 字数 487 浏览 6 评论 0原文

我有一个复选框,其值为“新”或“现有”公司。

$("input[name=company]:checked").val()

使用 jQuery 显示选中框的值。
现在,如果我这样做:

if ($("input[name=company]:checked").val() == "new") {
    is_new_company = true;
} else { 
    is_new_company = false; 
}
alert(is_new_company);

我会得到正确的布尔值。
走捷径:

($("input[name=company]:checked").val() == "new") ? is_new_company = true : is_new_company = false;

我什么也没得到..这是为什么?

I have a checkbox couple with values "new" or "existing" company.

$("input[name=company]:checked").val()

with jQuery shows me the value of the checked box.
Now if I do:

if ($("input[name=company]:checked").val() == "new") {
    is_new_company = true;
} else { 
    is_new_company = false; 
}
alert(is_new_company);

I get the correct booleans.
Doing the shortcut:

($("input[name=company]:checked").val() == "new") ? is_new_company = true : is_new_company = false;

I get nothing.. Why is that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只等公子 2024-09-17 17:30:44

你为什么不这样做:

is_new_company = $("input[name=company]:checked").val() == "new";

我在 Firebug 控制台上尝试了你的代码,它工作正常:(input[name=q] 是此页面右上角的搜索框)

var x;
$("input[name=q]").val() == "asd" ? x = "t r u e" : x = "f a l s e";
console.log(x);//worked as expected

顺便说一句,我认为以下内容更具可读性(当然,我只将其用于非布尔值):

x = $("input[name=q]").val() == "asd" ? "t r u e" : "f a l s e";

Why don't you just do:

is_new_company = $("input[name=company]:checked").val() == "new";

I tried your code on Firebug console and it works fine: (input[name=q] is the search box at the top right corner of this page)

var x;
$("input[name=q]").val() == "asd" ? x = "t r u e" : x = "f a l s e";
console.log(x);//worked as expected

By the way, I consider the following to be more readable (I'd use it only for non-boolean values, of course):

x = $("input[name=q]").val() == "asd" ? "t r u e" : "f a l s e";
晌融 2024-09-17 17:30:44

尝试

is_new_company = ($("input[name=company]:checked").val() == "new") ?  true : false;

Try

is_new_company = ($("input[name=company]:checked").val() == "new") ?  true : false;
笔芯 2024-09-17 17:30:44
is_new_company = ($("input[name='company']:checked").val() == "new") ? true : false;
is_new_company = ($("input[name='company']:checked").val() == "new") ? true : false;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文