我正在编写一个面向对象的 jquery 插件。我有一个类,我正在访问这个类,在插件中创建一个对象。我想在不使用元素数据的情况下访问这个对象,因为我需要学习调用插件时指定的元素的“大小”选项。
有些人将他们的对象放在元素数据上,如下所示:
element.data('myplugin', myplugin);
并像这样访问这个对象:
$(element).data('myplugin').get_size();
但是我想使用这样的东西:
$(element).get_myplugin_obj().get_size();
是否有可能做到这一点?我找不到任何这样做的例子。
可以说以下代码是我的插件。某些输入区域调用此插件。当用户在输入区域写信时,插件会使文本“hello”的“font-size”变大。因此,“你好”的信息越来越大。giveerror.js 中的另一个函数查找第一个给定大小并计算最大大小。所以这个插件需要通过使用它的 MyPluginClass 对象来访问每个元素的给定“大小”选项。
myplugin.js:
(function($) {
var MyPluginClass = function(element, customOptions)
{
var elem = $(element);
var obj = this;
var options = $.extend({
size: 1
}, customOptions || {});
/** public method **/
this.addMyPlugin = function() {
elem.after('<br /><span class="hello" style="font-size:'+options.size+'px">hello</span>');
calculate(elem);
elem.change(function() {
calculate(this);
});
elem.keyup(function(){
calculate(this);
});
};
/** private method */
var calculate = function(obj){
var length = $(obj).val().length;
var newsize = options.size + length;
$(obj).nextAll('.hello:first').css('font-size',newsize);
return;
};
/** public method to get max size value **/
this.get_size = function() {
return options.size;
};
/** public method to get object of this class for specific element **/
this.get_myplugin_obj = function() {
return obj;
};
};
$.fn.myPlugin = function(customOptions)
{
return this.each(function()
{
var element = $(this);
/** create an object for MyPluginClass **/
var MyPluginClassObj = new MyPluginClass(this, customOptions);
MyPluginClassObj.addMyPlugin();
});
};
})(jQuery);
给错误.js:
function validate_hello_size_func (element, error_message)
{
var first_given_size = $(element).get_myplugin_obj().get_size();
var threshold = first_given_size * 3;
//var threshold = 10;
var current_size_px = $(element).nextAll('.hello:first').css('font-size');
var current_size = parseInt(current_size_px.substr(0,current_size_px.length-2), 10);
if(current_size > threshold){
if(!$(element).next().hasClass('error'))
$(element).after('<span class="error" style="color:red">'+error_message+'</span>');
} else {
if($(element).next().hasClass('error'))
$(element).next().remove();
}
}
索引.php:
<html>
<head>
<title>Hello</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="myplugin.js"></script>
<script type="text/javascript" src="giveerror.js"></script>
<script type="text/javascript">
$(document).ready ( function ( ) {
$('#input1').myPlugin({
size: 5
});
$('#input2').myPlugin();
$('#input1').bind ( 'change', function() {
validate_hello_size_func (this, 'You exceeded the limit');
});
$('#input2').bind ( 'change', function() {
validate_hello_size_func (this, 'You exceeded the limit');
});
});
</script>
</head>
<body>
<div id="div1">
<input id="input1" type="text" name="input1" value="">
</div>
<div id="div2">
<input id="input2" type="text" name="input2" value="">
</div>
<br />
<input type="submit" name="submit" value="OK">
</body>
</html>