我是 Javascript 新手,如有任何帮助,我们将不胜感激。
我收到一条错误消息,指出不是 formValidation 不是函数,并且在控制台中我看到以下内容: ReferenceError:未定义要求 在portfolio/js/script.js:12:23
以下是包结构:
Portfolio
js
script.js
formValidation.js
index.html
我已将 script.js 添加到我的 html 页面
<script src="js/script.js"></script>
FormValidation.js(导出)
var FormValidation = function () {
var name = document.forms["contact"]["name"].value;
function nameValidation(name) {
if(name=="") {
alert("Enter name, required");
return false;
}else if(name==[0-9]) {
alert("Only alphabets");
}
return true;
}
nameValidation(name);
};
module.exports = FormValidation;
script.js(调用formValidation.js)
'use strict';
var FormValidation = require("./formValidation");
index.html
<form name="contact" action="#" method="post" enctype="text/plain">
<input type="text" name="name" placeholder="NAME"></br>
<input type="text" name="email" placeholder="EMAIL" required></br>
<input type="text" name="phoneNumber" placeholder="PHONE-NUMBER"></br>
<input type="text-box" name="message" placeholder="MESSAGE"></br>
<button id="submit" class="btn btn-primary" type="submit" onclick="return FormValidation()"><i class="fa fa-paper-plane">Submit</i></button></br>
</form>
</div>
<script src="js/script.js"></script>
</body>
</html>
谁能告诉我错误是什么?为什么我无法在 onclick 事件中从 html 页面调用 FormValidation()?
最佳答案
如果没有像browserify这样的工具,你就不能这样做。
您必须将另一个类似的脚本添加到您的 html 文件中。如果您使用的是node.js(后端),那么 require 可以毫无问题地工作,但是对于客户端,您需要像 browserify 这样的工具。
这是无浏览器的解决方案:
<script src="js/formValidation.js"></script>
关于javascript - 从“提交”按钮调用 Javascript 验证功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577629/