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.:
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下一篇: jQuery条件链接