🌐 AI搜索 & 代理 主页
Skip to content

Commit f6a0bf6

Browse files
committed
Added support for .data(Object), overwriting the existing data object. Fixes #4284.
1 parent 4e27f17 commit f6a0bf6

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

src/data.js

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,21 +37,24 @@ jQuery.extend({
3737

3838
// Avoid generating a new cache unless none exists and we
3939
// want to manipulate it.
40-
if ( cache[ id ] ) {
40+
if ( typeof name === "object" ) {
41+
elem[ expando ] = id;
42+
thisCache = cache[ id ] = jQuery.extend(true, {}, name);
43+
} else if ( cache[ id ] ) {
4144
thisCache = cache[ id ];
4245
} else if ( typeof data === "undefined" ) {
4346
thisCache = emptyObject;
4447
} else {
4548
thisCache = cache[ id ] = {};
4649
}
47-
50+
4851
// Prevent overriding the named cache with undefined values
4952
if ( data !== undefined ) {
5053
elem[ expando ] = id;
5154
thisCache[ name ] = data;
5255
}
53-
54-
return name ? thisCache[ name ] : thisCache;
56+
57+
return typeof name === "string" ? thisCache[ name ] : thisCache;
5558
},
5659

5760
removeData: function( elem, name ) {
@@ -100,6 +103,11 @@ jQuery.fn.extend({
100103
data: function( key, value ){
101104
if ( typeof key === "undefined" && this.length ) {
102105
return jQuery.data( this[0] );
106+
107+
} else if ( typeof key === "object" ) {
108+
return this.each(function() {
109+
jQuery.data( this, key );
110+
});
103111
}
104112

105113
var parts = key.split(".");

test/unit/data.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ test("expando", function(){
2525
});
2626

2727
test("jQuery.data", function() {
28-
expect(6);
28+
expect(8);
2929
var div = jQuery("#foo")[0];
3030
equals( jQuery.data(div, "test"), undefined, "Check for no data exists" );
3131

@@ -43,6 +43,10 @@ test("jQuery.data", function() {
4343

4444
jQuery.data(div, "test", null);
4545
ok( jQuery.data(div, "test") === null, "Check for null data");
46+
47+
jQuery.data(div, { "test": "in", "test2": "in2" });
48+
equals( jQuery.data(div, "test"), "in", "Verify setting an object in data." );
49+
equals( jQuery.data(div, "test2"), "in2", "Verify setting an object in data." );
4650
});
4751

4852
test(".data()", function() {
@@ -114,6 +118,16 @@ test(".data(String) and .data(String, Object)", function() {
114118
$elem.removeData();
115119
});
116120

121+
test(".data(Object)", function() {
122+
expect(2);
123+
124+
var div = jQuery("<div/>");
125+
126+
div.data({ "test": "in", "test2": "in2" });
127+
equals( div.data("test"), "in", "Verify setting an object in data." );
128+
equals( div.data("test2"), "in2", "Verify setting an object in data." );
129+
});
130+
117131
test("jQuery.removeData", function() {
118132
expect(1);
119133
var div = jQuery("#foo")[0];

0 commit comments

Comments
 (0)