最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript ternary operators for method calls - Stack Overflow

programmeradmin4浏览0评论

I would like to be able to do this:

var b = $(this).is(':checked')
$('.perspective-col'). (b) ? show() : hide()

instead of

var b = $(this).is(':checked')
if(b) {    
    $('.perspective-col').show() 
} else {
    $('.perspective-col').hide()
}

Am I wishing for too much? Or is there some wonderful javascript syntax I haven't found yet? Or am I right in thinking that no such thing exists in JQuery thus far? (I'm using JQuery 1.9.0)

I would like to be able to do this:

var b = $(this).is(':checked')
$('.perspective-col'). (b) ? show() : hide()

instead of

var b = $(this).is(':checked')
if(b) {    
    $('.perspective-col').show() 
} else {
    $('.perspective-col').hide()
}

Am I wishing for too much? Or is there some wonderful javascript syntax I haven't found yet? Or am I right in thinking that no such thing exists in JQuery thus far? (I'm using JQuery 1.9.0)

Share Improve this question edited Aug 5, 2013 at 19:19 Meredith asked Jul 2, 2013 at 4:03 MeredithMeredith 4,4545 gold badges36 silver badges58 bronze badges 1
  • 1 Another option, different from the current answers, is to use: $.fn[b ? "show" : "hide"].call($(".perspective-col")) – Ian Commented Jul 2, 2013 at 4:21
Add a comment  | 

2 Answers 2

Reset to default 21

You can use this :

var b = $(this).is(':checked')
$('.perspective-col')[b ? 'show' : 'hide']()

You can call jQuery function by passing a string into the bracket []. Just insert a condition inside to decide which string you pass!

In general,

<any expression>.property

is equivalent to:

<any expression>['property']

The difference is that you can replace the literal 'property' in the brackets with an expression that calculates the property name. jQuery methods are just properties whose values happen to be functions.

But I actually hate that practice. You can also use jQuery .toggle()

jQuery has a method that does what you want called toggle():

$('.perspective-col').toggle(b);
发布评论

评论列表(0)

  1. 暂无评论