我正在尝试使用 knockout 将我的 html 按钮绑定(bind)到函数。该函数仅在单击按钮时弹出警报消息,但该函数在页面加载时执行。
这是我的 HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type='text/javascript' src='knockout-2.2.0.js'></script>
<script type='text/javascript' src='studentapp.js'></script>
</head>
<body>
<div class="container">
<div class="new_student">
<input type="text" class="name" placeholder="name" data-bind="value: person_name, hasfocus: person_name_focus()">
<input type="text" class="age" placeholder="age" data-bind="value: person_age">
<button data-bind="click: createPerson">Create</button>
</div>
</body>
</html>
这是我的js:
function createPerson(){
alert("Name ");
};
ko.applyBindings(new createPerson());
控制台显示以下内容:
Uncaught TypeError: Cannot read property 'nodeType' of null
有什么想法吗?
最佳答案
View 模型应该如下所示
var createPerson = function(){
var self = this;
self.name = "Mike";
self.sendAlert = function(){
alert(self.name);
};
};
ko.applyBindings(new createPerson());
然后你的按钮就可以使用
<button type="button" data-bind="click:sendAlert"></button>
关于javascript - 页面加载时执行的单击功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30462115/