gpt4 book ai didi

jquery - 访问 jQuery 插件数据

转载 作者:行者123 更新时间:2023-12-03 22:50:34 27 4
gpt4 key购买 nike

jQuery documentation建议使用 data() 存储每个 DOMElement 的附加信息。但我很难以良好的方式访问保存的数据。

当我调用其他函数时范围会发生变化,这让我迷失了方向:)

(function ($) {
var methods = {
init: function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data('myPlugin');

if (!data) {
$(this).data('myPlugin', {
testValue: true
});

data = $this.data('myPlugin');
}
});
},

testFunction: function () {
console.log('t: '+$(this).data('myPlugin').testValue);
methods.otherFunction();
},

otherFunction: function () {
console.log('o: '+$(this).data('myPlugin').testValue);
}
};

$.fn.myPlugin = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.myPlugin');
}
};

})(jQuery);

$(document).ready(function () {
$('body').myPlugin();
$('body').myPlugin('testFunction');
});

控制台输出:

t: true
Uncaught TypeError: Cannot read property 'testValue' of undefined

最佳答案

您需要使用

        methods.otherFunction.apply(this);

而不是

        methods.otherFunction();

使范围正确。

演示:http://jsfiddle.net/ayNUD/

关于jquery - 访问 jQuery 插件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6940184/

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