我一直收到错误'验证不是函数'
function someObj( nameOfObj ) {
this.nameOfObj = nameOfObj;
var create = '<input id=' + nameOfObj + '>';
document.write(create);
someObject.prototype.validate = function( ) {
//nonsense
}
jQuery( '#' + this.nameOfObj ).bind( 'input', function( ) {
this.validate( ); //or validate( ); <------- Not working here
} );
}
我想在用户输入时创建一个自我验证<input>
的对象,它将执行valitdate( )
并且我想在实例化期间绑定此验证。
答案 0 :(得分:0)
真的需要使用原型吗?它似乎以这种方式工作:
function someObj( nameOfObj ) {
this.nameOfObj = nameOfObj; //changed here
var create = '<input id=' + nameOfObj + '></input>';
document.write(create);
this.validate = function( ) { //changed here
//nonsense
}
jQuery( '#' + this.nameOfObj ).bind( 'input', function( ) {
this.validate( ); //or validate( );
} );
}
答案 1 :(得分:0)
您使用的是旧版JQuery吗?从版本1.7开始,on方法优先于bind。
你没有在构造函数中提供validate函数,我的猜测是你无法使它工作,因为绑定函数中的this
引用了Element。这是你应该怎么做的:
function someObj( nameOfObj ) {
this nameOfObj = nameOfObj;
//there are better ways of doing this:
// http://api.jquery.com/?s=append
var create = '<input id=' + nameOfObj + '></input>';
document.write(create);
var me = this;
jQuery( '#' + this.nameOfObj ).bind( 'input', function( ) {
me.validate( ); //or validate( ); <------- Not working here
} );
}
someObject.prototype.validate = function( ) {
console.log("and this is now:",this);
//nonsense
}
构造函数,原型和this
here的价值简介。