JQuery Extension Help - Adding Conditional Statements
Im trying to write a JQuery wrapper extension that takes a content div and then shows it modally. Im having a bit of trouble getting it to work. It seems to work when I daisychain everything but when I try to use more than one line I break it. The problem with daisychaining is I don't know how to get the conditionals in there.
This doesnt work
(function ($) {
$.fn.showAsModal = function () {
var ret = this.css({ 'position': 'absolute', 'top': '400px', 'left': '100px', 'z-index': '9001' });
if (this.parent('.modal-container').size() <= 0) ret = this.wrap("<div style=\"display:none;\" class=\"modal-container\"></div>");
if (this.siblings('.modal-mask').size() <= 0) ret.parent().insertAfter("<div style=\"width:" + $(document).width() + "px;height:" + $(document).height() + "px;\" class=\"modal-mask\"></div>");
return ret;
};
})(jQuery);
This does
(function ($) {
$.fn.showAsModal = function () {
return this.css({ "position": "absolute", "top": "400px", "left": "100px", "z-index": "9001" })
.wrap("<div style=\"display:none;\" class=\"modal-container\"></div>")
.parent().show()
.append("<div style=\"width:" + $(document).width() + "px;height:" + $(document).height() + "px;\" class=\"modal-mask\"></div>")
.end();
};
})(jQ开发者_开发技巧uery);
But I don't know how to get conditionals in there...
This is what i want to do:
Given
<div id="content">
This is a content window
</div>
I want to get
<div class="modal-container" style="">
<div id="content" style="position: absolute; top: 400px; left: 100px; z-index: 9001;">
This is a content window
</div>
<div class="modal-mask" style="width: 1680px; height: 897px;">
</div>
</div>
when I do $('#content').showAsModal();
You could try this:
(function ($) {
$.fn.showAsModal = function () {
return this.each(function(){
var self = $(this)
self.css({'position': 'absolute', 'top': '400px', 'left': '100px', 'z-index': '9001'});
if (self.parent('.modal-container').length <= 0)
self.wrap("<div style=\"display:none;\" class=\"modal-container\"></div>");
if (self.siblings('.modal-mask').length <= 0)
self.parent().append("<div style=\"width:" + $(document).width() + "px;height:" + $(document).height() + "px;\" class=\"modal-mask\"></div>");
});
};
})(jQuery);
this.each()
will run on every element that jquery selects.
You can't assign a value to this
, and return ret;
returns undefined
because ret
is not defined. Maybe you want to do something like this:
var ret = this.css(...);
...
return ret;
精彩评论