我正在验证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?
}
}
};发布于 2012-01-19 05:09:42
在您的函数中传递txtField参数,在processNumber函数中使用它而不是this:
function processNumber( txtField ) {
if (!isNan(txtField )) {
alert("not a number");
txtField.focus();
}
}您还可以在jQuery.fn.DateHelper函数的.each()循环内声明processNumber函数,但不必如此,您可以在.each()外部声明该函数,任何运行此插件的元素都可以访问该函数。
更新
您的代码可以工作,但是有几个语法错误:
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
};这是一个演示:http://jsfiddle.net/uQ45E/6/
https://stackoverflow.com/questions/8917422
复制相似问题