我想通过单击并按 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();
}
})
})
最佳答案
指令:
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">
我不确定“keyup”和“keypress”是否适用于 div,您可以尝试使用表单中的所有输入元素:
<input ng-model="task.item" common-key-enter="addTask()" type="text" id="item" class="form-control autocomplete"/>
关于javascript - 通过点击和键盘输入实现功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51258838/