[英]JavaScript variable is undefined after being passed in a function
Hi I am working with a function and I just can't see what the problem is, help please? 嗨,我正在使用一个函数,但是我看不出问题出在哪里,请帮忙吗?
This is the JavaScript function to check the length of an input. 这是用于检查输入长度的JavaScript函数。
function checkLength(o, min, max)
{
if ( o.val().length > max || o.val().length < min )
{
$("#uper_length_stud").show()
return false;
}
else
{
return true;
}
}
under it is a code which calls it. 它下面是一个调用它的代码。
$("#signin").click(function(e) {
var name = $("#up_stud_fname").val(), x;
x = checkLength(name, 3, 50);
//other codes follow
}
It says at part o.val() that o is undefined. 它在o.val()部分说o是未定义的。 Though I think it is passed correctly?
虽然我认为传递正确? What seems to be the problem?
似乎是什么问题?
The Html part NAME: Update
HTML部件名称:更新
In checkLength()
you have not passed any thing. 在
checkLength()
您没有传递任何东西。
Try to pass all arguments to it 尝试将所有参数传递给它
pass three parameters to the function 将三个参数传递给函数
Here function wants 3 parameters ,and you are not passing it,so It says undefined 这里的函数需要3个参数,并且您没有传递它,所以它说undefined
o, min, max o,最小,最大
Try this One Check this fiddle http://jsfiddle.net/pratbhoir/9QTYk/ 试试这个,检查这个小提琴http://jsfiddle.net/pratbhoir/9QTYk/
Html Code HTML代码
<input id='firstName' />
<button id="btn"> Button</button>
JavaScript Code JavaScript代码
$("#btn").click(function() {
var name = $('#firstName').val();
x = checkLength(name,1,4);
//other codes follow
});
function checkLength(o, min, max)
{
if ( o.length > max || o.length < min )
{
//$("#uper_length_stud").show()
return false;
}
else
{
return true;
}
}
You can takeout the .val()
from your if condition because name
is a string which you are passing: 您可以从if条件中取出
.val()
,因为name
是您要传递的字符串:
function checkLength(o, min, max){
if ( o.length > max || o.length < min ){
$("#uper_length_stud").show();
return false;
}
}
and i think you don't need the else part and make sure that your function is in global scope. 而且我认为您不需要else部分,并确保您的功能在全局范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.