jQuery的VAL()上的自定义对象的方法
-
19-09-2019 - |
题
我有称为ValueBox我喜欢这个创建的对象:
function ValueBox(params) {
...
$.extend(true, this, $('/* some HTML elements */'));
...
var $inputBox = $('input[type=text]', this);
...
this.val = function(newValue) {
if(typeof newValue == "number") {
$inputBox.val(newValue);
$inputBox.change();
} else {
return parseFloat($inputBox.val());
}
}
}
我有在其上触发每当$inputBox
变化的特定ValueBox实例的变化事件,但是改变的回调函数是无法使用VAL()方法在我的类。我认为通过使用$(this).val()
那我打电话jQuery的VAL()方法,这当然是行不通的。是否有可能访问I定义的VAL()方法
解决方案
当调用$inputBox.change()
,传递给它ValueBox
对象。然后调用上val
。这样,你就不必担心jQuery的控制之内划定范围的问题。
其他提示
$.fn.yourpluginscope.originalVal = $.fn.val;
$.fn.extend({
val: function (value) {
if (/* detect your plugin element */)
{
if (value == undefined)
return /* getter */;
return $.fn.yourpluginscope.originalVal.call(/* setter */, value);
}
return $.fn.yourpluginscope.originalVal.call(this, value);
}
});
适当的方法来延伸 “天然” 的jQuery方法
如果你是在为你的插件扩展VAL()很感兴趣,你可以尝试类似如下:
让我们假设你已经设置并在您的插件的最外层元素属性“值”。
jQuery.fn.extend({ val: function(newValue) {
if (newValue == null) {
return $(this).attr("value");
} else {
$(this).attr("value", newValue);
}
}
});
如果我的插件实例的id是myValueBox然后我将能够以下面的方式使用VAL:
$( “#myValueBox”)。VAL()
它为我,但我不知道它是否符合您的要求。
我想你应该尝试类似的东西。
function ValueBox(params) {
...
$.extend(true, this, $('/* some HTML elements */'));
...
this.inputBox = $('input[type=text]', this);
...
}
ValueBox.prototype.val = function(newValue) {
if(typeof newValue == "number") {
this.inputBox.val(newValue);
this.inputBox.change();
} else {
return parseFloat(this.inputBox.val());
}
};
// then this should work
var test = new ValueBox();
test.val(123);
在原型定义公共方法,其中所有的都ValueBox
功能是私有的;
不隶属于 StackOverflow