我正在验证html表单上的文本输入,并且如果文本无效则想要关注并选择文本。
如果我的验证功能看起来像(只是一个例子):
jQuery.fn.DateHelper = function(text){
return this.each(function(){
//Make sure we're dealing with text-based form fields
if(this.type != 'text')
return;
// call the processNumber function when the onBlur event is fired and there is a value in the field.
$(this).blur(function() {
if (this.value != '')
processNUmber(this);
});
function processNumber( txtField ) {
if (!isNan(txtField )) {
alert("not a number");
this.focus(); // this does not work.
// how to select text?
}
}
};
答案 0 :(得分:1)
在您的函数中,您传递txtField
参数,在this
函数中使用processNumber
而不是function processNumber( txtField ) {
if (!isNan(txtField )) {
alert("not a number");
txtField.focus();
}
}
:
processNumber
此外,您在.each()
函数中的jQuery.fn.DateHelper
循环内声明.each()
函数(不一定是这种情况),您可以在{{1}之外声明该函数这个插件运行的任何元素都可以访问它。
您的代码函数有多种语法错误:
jQuery.fn.DateHelper = function(text){
return this.each(function(){
//Make sure we're dealing with text-based form fields
if(this.type != 'text') return;
// call the processNumber function when the onBlur event is fired and there is a value in the field.
$(this).blur(function() {
if (this.value != '') processNumber(this);//you were calling the processNUmber function, which doesn't exist
}).focus(function () {
this.select();
});
function processNumber( txtField ) {
//isNan is broken: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN
//also txtField is a DOM element, not a string
txtField.value = txtField.value.replace(/[^0-9.]/g, "");
if (txtField.value.length > 0) {
alert("not a number");
txtField.focus();
}
}
});//this was omitted
};