gpt4 book ai didi

javascript - 使用 new 运算符将 data() 添加到 html 元素

转载 作者:行者123 更新时间:2023-11-30 16:52:50 25 4
gpt4 key购买 nike

我只是写了一个非常简单的片段来理解 jQuery data() 的功能,代码如下:

$(function () {     
carousel = function() {
this.prop1 = 1;
this.prop2 = 'two';
this.prop3 = 3;
}
var _str = $('#test'),
$str_data = _str.data();
console.log($str_data);
data = _str.data('carousel');

if (!data) _str.data('carousel' , new carousel());
console.log(data);

if (!data) {
console.log('no data');
}
});

现在,这段代码的目标是使用 new 运算符将 data() 添加到 div 元素,然后检查是否添加了那条数据,但是在我的代码片段中,尽管我使用以下代码行将数据添加到 div 元素:

if (!data) _str.data('carousel' , new carousel()); 

当我再次检查下一行是否确实添加了数据时:

if (!data) {
console.log('no data');
}

测试通过,这意味着没有添加数据。那我错过了什么?

最佳答案

如果没有数据,您正在更新与元素关联的数据,但 data 变量引用的值未更新,这就是为什么它仍然给出 undefined 作为其值(value)。

$(function () {

var carousel = function () {
this.prop1 = 1;
this.prop2 = 'two';
this.prop3 = 3;
}

var _str = $('#test'),
$str_data = _str.data();

console.log($str_data);

var data = _str.data('carousel');

if (!data) {
//create a new carousel and assign it to data so that it gets a new value
data = new carousel();
//store the new carousel value
_str.data('carousel', data);
}

console.log(data);

if (!data) {
console.log('no data');
}

});

演示:Fiddle

关于javascript - 使用 new 运算符将 data() 添加到 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30235768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com