2
我正在编写需要维护状态的jQuery
插件。页面上会有多个实例,但每个实例都有与数据库中的键相关的不同数据。我试图用jQuery网站上的例子作为我的出发点,但遇到了一些困难。这里的'hid'和'hnid'是我感兴趣的关键值。在制作过程中,我会通过选项将它们传递给它们。但我的问题是,当我点击保存按钮并运行'save'方法时,如何获得我的数据键,hid和hnid?现在,当我运行代码时,我得到的数据为空。用jquery插件维护状态
(function($) {
var settings = {
'background-color': 'blue'
};
var saveData = function() {
var data = $(this).data('inknote');// now this refers to save button so has no 'data' associated with it.
console.log('data', data);
}
var methods = {
init: function(options) {
return this.each(function() {
if (options) {
$.extend(settings, options);
}
var $this = $(this),
data = $this.data('inknote');
// If the plugin hasn't been initialized yet
if (!data) {
var startData = {
target: $this,
hid: 1,
hnid: 2
};
$this.data('inknote', startData);
}
var $messageDiv = $('<div>').addClass('messages').html(' ');
/* am I calling the save method properly here ?*/
var $saveButton = $('<input>').attr('type', 'button').attr('value', 'Save').bind('click', function() { methods['save'].apply(this); });
var $printButton = $('<input>').attr('type', 'button').attr('value', 'Print').bind('click', function() { methods['print'].apply(this); });
var $lockStatus = $('<div>').addClass('lock').addClass('unlocked').html(' ');
$this.append($messageDiv).append($saveButton).append($printButton).append($lockStatus);
});
},
save: function(el) {
return $(this).each(function() {
saveData(this);
});
},
print: function(el) {
return false;
}
};
$.fn.inknote = 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.inknote');
}
};
})(jQuery);
感谢您提供您的答案。这让我朝着正确的方向前进。您的代码更清楚地表明数据项必须附加到特定的dom元素。同样,click事件在插入了插件的原始元素中传递的方式也是如此。我只是将数据“封装”移动到插件内部,并通过设置传递给密钥。 http://jsfiddle.net/voam/uJnQj/ – voam 2010-12-27 19:24:51