gpt4 book ai didi

javascript - 我不明白 jQuery.data() 方法

转载 作者:行者123 更新时间:2023-11-30 14:03:41 25 4
gpt4 key购买 nike

.data() - 将数据附加到选定元素或从中获取数据。 jQuery 中的一个方法

问题:

1) 这个方法的目的是什么?
2) 当我运行它时,我看到没有创建 data-* 属性。那么data-*属性和jQuery中data()方法创建的数据有什么区别呢?

<!--code from w3school -->

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("div").data("greeting", "Hello World");
});
$("#btn2").click(function(){
alert($("div").data("greeting"));
});
});
</script>
</head>
<body>

<button id="btn1">Attach data to div element</button><br>
<button id="btn2">Get data attached to div element</button>

<div></div>

</body>
</html>

最佳答案

一个用例可以围绕存储实例,下面是伪代码

function SomePlugin(element, options) {
this.$el = $(element);
this.options = options;
}

SomePlugin.prototype.method = function() {
this.$el.toggleClass(this.options.cssClass);
}

$.fn.somePlugin = function(options) {
var somePluginInstance = new SomePlugin(this, options);
// store instance as data
this.data("somePlugin", somePluginInstance);
}

用法:

$(".element").somePlugin({});

var pluginInstance = $(".element").data("somePlugin");

pluginInstance.method();

关于javascript - 我不明白 jQuery.data() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860458/

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