【发布时间】:2020-04-14 07:12:18
【问题描述】:
这是我第一次尝试使用 javascript 中的类创建 mvc 模型。
通过我的控制器对象应用程序的模型对象的 getFormValues() 方法,我想读取所有输入文件的值。然后我想将它们保存到我的控制器对象的模型对象的表单值属性中。这行不通!
console.log(app.model.getFormValues()); 行向我显示了带有表单值的数组。
console.log(app.model.formValues); 行显示了一个空数组。
如何将 getFormValues 方法中的数组存储在模型对象的属性 formValues 中?
我的 HTML:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<form>
<div class="row">
<div class="col">
<input type="text" class="form-control" placeholder="First name">
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Last name">
</div>
</div>
</form>
<button id="verification"> Verify</button>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="js.js"></script>
</body>
</html>
我的 JS/Jquery:
class Model {
constructor() {
this.formValues = this.getFormValues();
}
getFormValues() {
let $inputs = $("input");
var formValues = [];
$inputs.each(function(index) {
let value1 = $(this).val();
formValues.push(value1);
});
return formValues;
}
}
class View {
constructor() {}
}
class Controller {
constructor(model, view) {
this.model = model
this.view = view
}
}
const app = new Controller(new Model(), new View());
check = function () {
console.log(app.model.getFormValues());
console.log(app.model.formValues);
}
$("#verification").on("click", check);
提前问候和感谢 费边
【问题讨论】:
-
您的模型对象是否可能在 DOM 元素存在之前创建,因此当构造函数运行并且您设置
this.formValues的值时$("input");将为空? -
不,只是用 $( document ).ready(function() {....});结果相同。
-
只需在构造函数的末尾放一个
console.log(this.formValues)看看它是否正确。如果是,则在您的check()函数中执行console.log(app.model)以查看这是否是您期望的对象。这是一个简单的调试,可以查看属性是否没有正确填充,或者您是否稍后没有查看正确的对象,或者其他内容是否发生了变化。由于您没有向我们展示您的所有代码,我们无法运行它来调试它。你必须这样做。 -
那么,在您创建 Model 类时,您的表单元素是空的,对吧?还没有任何东西进入它们。那么,它们的值自然会是空的,对吧?
-
我发布了整个 JS 代码,HTML 代码现在完全可见
标签: javascript jquery arrays class es6-class