Javascript 在验证函数中将html id作为参数传递
我有一个表单的jQuery验证函数。所有字段的验证逻辑都是相同的,不同的是字段名。我可以将html元素的ID作为方法参数传递吗?我的意思是-我知道我可以,但是如何把它放在#之后呢Javascript 在验证函数中将html id作为参数传递,javascript,jquery,Javascript,Jquery,我有一个表单的jQuery验证函数。所有字段的验证逻辑都是相同的,不同的是字段名。我可以将html元素的ID作为方法参数传递吗?我的意思是-我知道我可以,但是如何把它放在#之后呢 函数validateFieldName(){ var nameFieldLength=$(“#nameField”).val().length; 如果(cgLength15){ $(“#nameFieldLab”).html(“错误”); $(“#nameFieldLab”).show(); }否则{ $(“#name
函数validateFieldName(){
var nameFieldLength=$(“#nameField”).val().length;
如果(cgLength<3 | | cgLength>15){
$(“#nameFieldLab”).html(“错误”);
$(“#nameFieldLab”).show();
}否则{
$(“#nameFieldLab”).hide();
}
}
我不想拥有的是单一功能,比如:
function validateField(formField, errorLabel){
var fieldLength = $("#formField").val().length;
if(cgLength < 3 || cgLength > 15){
$("#errorLabel").html("error");
$("#errorLabel").show();
}else{
$("#errorLabel").hide();
}
}
函数validateField(formField,errorLabel){
var fieldLength=$(“#formField”).val().length;
如果(cgLength<3 | | cgLength>15){
$(“#errorLabel”).html(“error”);
$(“#errorLabel”).show();
}否则{
$(“#errorLabel”).hide();
}
}
尝试简单的字符串连接:
function validateName(id) {
var nameFieldLength = $("#" + id).val().length; //Here.
....
}
我通过了一个不好的一个更好的通过
this
function validateName(that){
var nameFieldLength = $(that).val().length;
if(cgLength < 3 || cgLength > 15cgLength){
$(that).html("error");
$(that).show();
}else{
$(that).hide();
}
}
函数validateName(即){
var nameFieldLength=$(即.val().length;
如果(cgLength<3 | | cgLength>15cgLength){
$(that.html(“错误”);
$(that.show();
}否则{
$(that.hide();
}
}
function validateName(that){
var nameFieldLength = $(that).val().length;
if(cgLength < 3 || cgLength > 15cgLength){
$(that).html("error");
$(that).show();
}else{
$(that).hide();
}
}