我正在创建一个小型待办事项应用,并遇到一个问题,看起来警报消息在点击事件触发之前运行。看起来事件看起来并不像。任何人都可以告诉我为什么会这样吗?
(function() {
'use strict';
var MyTodo = {
init: function() {
this.cacheDom();
this.bindEvent();
this.addTask();
},
cacheDom: function() {
this.$title = $('#inpTitle');
this.$date = $('#inpDate');
this.$description = $('#inpDescription');
this.$addTaskBtn = $('#addTaskBtn');
this.$pending = $('#pending');
},
addTask: function() {
if (!this.$title.val()) {
alert('please enter title');
return;
}
var value = '<ul class="todo-task" id="todoList" draggable="true"><li><strong>' + this.$title.val() + '</strong></li>' +
'<li>' + this.$date.val() + '</li>' +
'<li>' + this.$description.val() + '</li></ul>';
this.$pending.append(value);
// empty inputs
this.$title.val('');
this.$date.val('');
this.$description.val('');
},
bindEvent: function() {
this.$addTaskBtn.on('click', this.addTask.bind(this));
}
};
MyTodo.init();
})();
答案 0 :(得分:0)
当您在this.addTask();
中调用init
时,init
方法将被调用,因此它将alert()
。从this.addTask
init()
次调用
(function() {
'use strict';
var MyTodo = {
init: function() {
this.cacheDom();
this.bindEvent();
},
cacheDom: function() {
this.$title = $('#inpTitle');
this.$date = $('#inpDate');
this.$description = $('#inpDescription');
this.$addTaskBtn = $('#addTaskBtn');
this.$pending = $('#pending');
},
addTask: function() {
if (!this.$title.val()) {
alert('please enter title');
return;
}
var value = '<ul class="todo-task" id="todoList" draggable="true"><li><strong>' + this.$title.val() + '</strong></li>' +
'<li>' + this.$date.val() + '</li>' +
'<li>' + this.$description.val() + '</li></ul>';
this.$pending.append(value);
// empty inputs
this.$title.val('');
this.$date.val('');
this.$description.val('');
},
bindEvent: function() {
this.$addTaskBtn.on('click', this.addTask.bind(this));
}
};
MyTodo.init();
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="todoWrapper" class="container">
<div class="todo" id="pending" ondrop="drop(event)" ondragover="allowDrop(event)">
<h3 class="text-center">Pending</h3>
</div>
<div class="todo" id="inProgress" ondrop="drop(event)" ondragover="allowDrop(event)">
<h3 class="text-center">In Progress</h3>
</div>
<div class="todo" id="completed" ondrop="drop(event)" ondragover="allowDrop(event)">
<h3 class="text-center">Completed</h3>
</div>
<div id="addTask" class="todo">
<h2 class="text-center">Add Task</h2>
<div>
<input type="text" name="" id="inpTitle" placeholder="title">
</div>
<div>
<textarea name="" id="inpDescription" cols="23" rows="3" placeholder="description"></textarea>
</div>
<div>
<input type="date" name="" id="inpDate" placeholder="due date">
</div>
<div>
<button id="addTaskBtn" class="btn btn-primary">Add Task</button>
<button id="clearTaskBtn" class="btn btn-primary">Clear Task</button>
</div>
<div class="delete" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<audio id="sfx" src="media/dump.wav"></audio>
</div>
</div>
&#13;