jQuery conditional chaining

Let's say I have the following jQuery code. It works great, but then I need to include the .after($('<div />')) only if var insertAfter equals true. Is there an elegant jQuery way of doing this?

$('#whatEver')
    .parent()
    .show()
    .width(123)
    .addClass('bebo')
    .before($('<div />'))
    .after($('<div />'))
    .parent()
    .addClass('bla');

尝试使用三元运算符:

.after(insertAfter ? $('<div />') : '')

You can extend jQuery library like this:

$(function () {
    $.fn.afterif = function (param, condition) {
        if (condition) {
            $(this).after(param);
        }
        return this;
    }
}(jQuery));

And use it like this:

var insertAfter = true;
$('#whatEver').afterif($('<div />'), insertAfter);

There are numerous examples, here on stack overflow on how to check if a variable is defined.:

  • Whether a variable is undefined
  • Find out if a Variable exists
  • How to determine if variable is 'undefined' or 'null'?
  • JavaScript check if variable exists (is defined/initialized)
  • Then you can use break and continue to control the flow.

    http://www.w3schools.com/js/js_break.asp

    链接地址: http://www.djcxy.com/p/76368.html

    上一篇: 检测一个Javascript变量是否真的未定义

    下一篇: jQuery条件链接