javascript初学者
我收到以下错误但无法查看代码有什么问题。我在之前的研讨会上做过类似的事情,他们还可以吗?我有"必需"在workshop12.js中运行,并希望用它来检查输入是否为空。我从w3schools http://www.w3schools.com/js/js_validation.asp
获取代码
JS
$( document ).ready(function() {
// Check that input is not empty
function required() {
var x = document.forms["loginForm"]["inputName"].value;
document.write (x);
if(x = " ") {
alert("Please input a value");
return false;
}
else {
alert("Correct");
return true;
}
}
});
HTML
<body>
<div class="container">
<div class="row">
<div class="col-sm-offset-2 col-sm-10 col-md-offset-3 col-md-6 col-lg-offset-3 col-lg-6">
<h2>Login form</h2>
</div>
<div class="clearfix visible-md clearfix visible-lg"></div>
</div>
<form name="loginForm" class="form-horizontal">
<div class="form-group">
<label for="inputName" class="col-sm-2 col-md-2 col-lg-3 control-label">Name</label>
<div class="col-sm-10 col-md-8 col-lg-6">
<input type="text" class="form-control" name="inputName" "id="inputName" placeholder="Name" onclick="required()">
<div class="col-md-2 col-lg-3"></div>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 col-md-2 col-lg-3 control-label">Email</label>
<div class="col-sm-10 col-md-8 col-lg-6">
<input type="email" class="form-control" id="inputEmail" placeholder="Email">
<div class="col-md-2 col-lg-3"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10 col-md-offset-3 col-md-9 col-lg-offset-3 col-lg-9">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
<script type="text/javascript" src="js/workshop12.js"></script>
</body>
答案 0 :(得分:4)
您的函数仅在ready
函数内的范围内,在该范围之外不可用。
您的元素正在全局范围内寻找该功能。将功能移到ready
功能之外,如下所示:
$( document ).ready(function() {
... whatever
});
// Check that input is not empty
function required() {
var x = document.forms["loginForm"]["inputName"].value;
document.write (x);
if(x = " ") {
alert("Please input a value");
return false;
}
else {
alert("Correct");
return true;
}
}
答案 1 :(得分:2)
你有一个范围问题。
Javascript中有不同类型的范围。
全局范围:每个函数都可以访问范围为全局的变量/函数。通常,您不希望将任何全局范围限定,因为在每个人都使用不同框架的时候,您永远不知道谁将变量写入全局范围。
全球范围的示例:
window.bla = "I am global scoped";
var globalVar = "I am also global scoped";
function accessGlobal(){
console.log (globalVar)
}
现在还有一个函数作用域:在函数中声明的变量是本地作用域的,不能从外部访问(如果你更像Java人员,可以把它看作私有变量)
function private(){
var privateVar = "I am a private var";
}
由于您使用了jQuery的onReady函数,因此无法全局访问您所需的函数。
见:
$( document ).ready(function() {
你看到了这个功能吗?因此,您所需的函数是函数作用域。
在您的情况下,我建议使用模块模式来防止污染全局范围。
试试这个:
var myModule = {};
myModule.required = function(){
var x = document.forms["loginForm"]["inputName"].value;
document.write (x);
if(x.length === 0) {
alert("Please input a value");
return false;
}
else {
alert("Correct");
return true;
}
}
并在HTML代码中,将replace required()与myModule.required();
一起使用顺便说一下,在你所要求的功能中,你犯了另一个错误。您尝试检查变量是否为空,如下所示:
if (x = " ")
在Javascript中,您需要使用==或更好的===检查变量。 (我在你的代码中改了这个)
==和===之间的区别仅在于===还会检查正确的类型。
E.g。
"1" == 1 //true
"1" === 1//false because string and number are different