I am using jQuery 1.7.1

I am just starting to use the JavaScript ternary operator to replace simple if/else statements. I have done so successfully in several places. I was surprised when I successfully made something else work when I thought for sure it wouldn't, but I tried anyway.

以下是原始声明:

function updateItem() {
    $this = $(this);
    var IsChecked = $this.hasClass("IsChecked");
    if (IsChecked == true){
        removeItem($this);
    } else {
        addItem($this);
    }
}

Here's the same function using the ternary operator:

function updateItem() {
    $this = $(this);
    var IsChecked = $this.hasClass("IsChecked");
    (IsChecked == true) ? removeItem($this) : addItem($this);
}

I was surprised because all of the examples I saw being used were merely setting variables like this:

x = (1 < 2) ? true : false;

我的问题是,这是否是"正常"使用,在大多数版本的JavaScript中是否有效?它会在哪里失败?它还有其他不太明显的用途吗?

UPDATE -- Thanks for the "real world" advice!!!

我将此函数用作我的函数:

function updateItem() {
    $this = $(this);
    $this.hasClass("IsChecked") ? removeItem($this) : addItem($this);
}

推荐答案

Heh, there are some pretty exciting uses of ternary syntax in your question; I like the last one the best...

x = (1 < 2) ? true : false;

这里使用三元是完全不必要的-您可以简单地写成

x = (1 < 2);

同样,三元语句的条件元素始终作为布尔值计算,因此可以表示:

(IsChecked == true) ? removeItem($this) : addItem($this);

Simply as:

(IsChecked) ? removeItem($this) : addItem($this);

In fact, I would also remove the IsChecked temporary as well which leaves you with:

($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);

As for whether this is acceptable syntax, it sure is! It's a great way to reduce four lines of code into one without impacting readability. The only word of advice I would give you is to avoid nesting multiple ternary statements on the same line (that way lies madness!)

Jquery相关问答推荐

如何使用 JQuery 将详细信息中的项目包装在容器中?

在学习 jQuery 之前学习 JavaScript 是个好主意吗?

[本机代码]是什么意思?

模糊事件阻止点击事件工作?

jQuery $(document).ready () 触发两次

jQuery从字符串中删除字符串

JQuery 仅在 Rails 4 应用程序中的页面刷新时加载

根据属性'data-sort'对jQuery中的div进行排序?

在不刷新页面的情况下更新网站的 CSS

调整浏览器大小时调整jqGrid的大小?

如何在 jQuery 中修改序列化的表单数据?

将字符串true和false转为布尔值

jQuery 如果 div 包含此文本,则替换该部分文本

更改占位符文本

如何让 JavaScript/jQuery Intellisense 在 Visual Studio 2008 中工作?

延迟jquery悬停事件?

检测夹点的最简单方法

如何将参数传递给 jQuery 中的事件处理程序?

调整浏览器大小时如何自动居中 jQuery UI 对话框?

jQuery向左滑动并显示