Per*_*ark 6 jquery jquery-plugins
的jQuery文档表明存储每一个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');
});
Run Code Online (Sandbox Code Playgroud)
控制台输出:
t: true
Uncaught TypeError: Cannot read property 'testValue' of undefined
Run Code Online (Sandbox Code Playgroud)
你需要使用
methods.otherFunction.apply(this);
Run Code Online (Sandbox Code Playgroud)
代替
methods.otherFunction();
Run Code Online (Sandbox Code Playgroud)
使范围正确.
| 归档时间: |
|
| 查看次数: |
3412 次 |
| 最近记录: |