我想通过单击并按Enter在对话框中执行Javascript函数。第一个作品。不幸的是,我无法正确实现功能(“保存”按钮的“ addTask()”)。
<div class="modal fade" id="add_new_task_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-new-item" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add new item</h4>
</div>
<div class="modal-body">
<ul class="alert alert-danger" ng-if="errors.length > 0">
<li ng-repeat="error in errors">
{{ error }}
</li>
</ul>
<div class="form-group">
<label for="quantity">Quantity</label>
<input ng-model="task.quantity" type="text" id="quantity" class="form-control"/>
</div>
<div class="form-group">
<label for="item">Item</label>
<input ng-model="task.item" type="text" id="item" class="form-control autocomplete"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" ng-click="addTask()">Save</button>
</div>
</div>
</div>
</div>
JavaScript
$(function(){
$('.modal-new-item').keypress(function(e){
if(e.which == 13) {
addTask();
}
})
})
答案 0 :(得分:1)
指令:
app.directive('commonKeyEnter', function() { return { restrict: 'A', scope: { commonKeyEnter: '&' }, link: function(scope, element, attrs) { element.bind('keyup keypress', function(event) { if (event.which === 13) { scope.$apply(function() { scope.$eval(attrs.commonKeyEnter); }); event.preventDefault(); } }); } }; });
HTML:
<div class="modal-dialog modal-new-item" common-key-enter="addTask()" role="document">
我不确定div上是否可以使用“ keyup”和“ keypress”,您可以尝试使用以下形式的所有输入元素:
<input ng-model="task.item" common-key-enter="addTask()" type="text" id="item" class="form-control autocomplete"/>
答案 1 :(得分:1)
我找到了解决方法:
<div class="form-group">
<label for="item">Items</label>
<input ng-model="task.item" type="text" ng-keyup="$event.keyCode == 13 && addTask()" id="item" class="form-control autocomplete"/>
</div>