Understanding $.extend (), different from the $.fn.extend () method
1.$.extend () method
The $.extend () method has two uses in jquery, the first being an extension method,
The second method is
Jquery.extend ([deep], Target, Object1, [objectn])
return value: Object
Merging 2 objects to get new target,deep is optional (recursive merge)
Merge settings and options, modify and return settings.
JQuery Code:
var settings = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" };jQuery.extend(settings, options);
Results:
settings == { validate: true, limit: 5, name: "bar" }
Describe:
Merge defaults and options without modifying the defaults.
JQuery Code:
var empty = {};var defaults = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" };var settings = jQuery.extend(empty, defaults, options);
Results:
settings == { validate: true, limit: 5, name: "bar" }empty == { validate: true, limit: 5, name: "bar" }
Extension in 2:
First, look at the code.
$(
function
(){
jQuery.extend({
modalshow:
function
(options) {
var
defaults = {
triggerID:
‘LoginShow‘
,
callback:
function
() { }
}<br>
//这里是$.extend的第二种用法<br> var opts = $.extend({},defaults, options);
if ($(
"#"
+ opts.triggerID)[0] ==
null
) {
var
$triggerBTN = $(
‘<input type="button" value="LoginShow" id=‘
+ opts.triggerID +
‘/>‘
);
$triggerBTN.bind(
"click"
,
function
() {
alert(opts.triggerID);
});
$(
"body"
).append($triggerBTN);
}
else
{
$(
"#"
+ opts.triggerID).bind(
"click"
,
function
() {
alert(opts.triggerID);
})
}
}
});
$.modalshow();
//这里是调用的地方,id为‘loginshow‘的button可以先不再HTML中添加可以自动生成
})
|
The second type of extension
$(
function
(){
jQuery.fn.extend({
modalshow:
function
(options) {
var
defaults = {
//这里的this是JQuery对象
triggerID:
this
.attr(
"id"
),
callback:
function
() { }
}<br>
//这里是$.extend的第二种用法<br> var opts = $.extend(defaults, options);
$(
"#"
+ opts.triggerID).bind(
"click"
,
function
() {
alert(opts.triggerID);
})
}
});
$(
"#loginShow"
).modalshow();
//这里是调用的地方,这里需要先在HTML中加入元素
})
|
jquery Add extension Method (Understanding $.extend (), different from $.fn.extend () method)