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

javascript - Conditionally passing options to a jquery function - Stack Overflow

programmeradmin3浏览0评论
$.fn.demo = function(options) {
    var defaults = {
        opacity: 50,
        width: '250px',
        height: '100px',
        color: 'red'
    }
  }

Is there any way to conditionally pass options to a function, like such:

$().demo({
opacity: 60,
if (div.length){
    width: '350px'
}
height: '100px'
});

Just curious what would be the best way to handle a situation where you may want to pass different options depending on circumstances. Thanks!

$.fn.demo = function(options) {
    var defaults = {
        opacity: 50,
        width: '250px',
        height: '100px',
        color: 'red'
    }
  }

Is there any way to conditionally pass options to a function, like such:

$().demo({
opacity: 60,
if (div.length){
    width: '350px'
}
height: '100px'
});

Just curious what would be the best way to handle a situation where you may want to pass different options depending on circumstances. Thanks!

Share Improve this question asked Jun 27, 2012 at 15:48 mstefmstef 1,1941 gold badge13 silver badges37 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 12

If it's simple enough you can use the ternary operation

$().demo({
    opacity: 60,
    width: div.length ? '350px' : '250px',
    height: '100px'
});

If it's more plicated you should just pose the parameter object outside of the function call.

var parameters = {
    opacity: 60,
    height: '100px'
};
if(div.length)
    parameters.width = '350px';
$().demo(parameters);
$.fn.demo = function(options) {
    var defaults = {
        opacity: 50,
        width: '250px',
        height: '100px',
        color: 'red'
    };
    options || (options = {});
    defaults = $.extend(defaults, options);
    ... function body...
}

When you use extend, it overwrites defaults and adds any arbitrary data, if it's present.

发布评论

评论列表(0)

  1. 暂无评论