我在下面输入以下代码:
<div class="search-container">
<input id="search-value" type="text" autocomplete="off" ng-model="vm.searchQuery" ng-focus="vm.searchBoxHasFocus = true" ng-blur="vm.searchBoxHasFocus = false" class="search-box-input ng-pristine ng-untouched ng-valid ng-empty" placeholder="Pesquisar" ng-enter="vm.goSearch()" ng-change="vm.getSuggestions()">
<div class="label-search" ng-click="vm.goSearch()"></div>
<button type="button" class="reset-search" ng-click="vm.clearQuery()"></button>
</div>
当我在输入中按“输入”时,如何调用JS函数?
答案 0 :(得分:0)
如果您希望在原始javascript中执行此操作,则可以使用以下绑定将整个文档的Enter键绑定到您要调用的函数。
// Load in the enter keybindings
document.onkeydown = function (e) {
switch (e.which || e.keyCode) {
case 13 : //Your Code Here (13 is ascii code for 'ENTER')
vm.clearQuery()
}
}
答案 1 :(得分:0)
您始终可以将其包装为表单并调用onsubmit,只需将vm.goSearch()更改为实际函数即可。
<form onsubmit="return function(){vm.goSearch();return false;};">
<div class="search-container">
<input id="search-value" type="text" autocomplete="off" ng-model="vm.searchQuery" ng-focus="vm.searchBoxHasFocus = true" ng-blur="vm.searchBoxHasFocus = false" class="search-box-input ng-pristine ng-untouched ng-valid ng-empty" placeholder="Pesquisar" ng-enter="vm.goSearch()" ng-change="vm.getSuggestions()">
<div class="label-search" ng-click="vm.goSearch()"></div>
<button type="button" class="reset-search" ng-click="vm.clearQuery()"></button>
</div>
</form>
答案 2 :(得分:0)
您可以尝试以下操作:
// Get the input field you want
var input = document.getElementById("search-value");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Cancel the default action, if needed
event.preventDefault();
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Trigger the button element with a click
document.getElementById("ElementId").click();
//or function call here
}
});
这是一个有用的提示
答案 3 :(得分:0)
尝试ng-keypress事件并读取keyCode = 13进行输入。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" >
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName" ng-keypress="keypress($event)">
<br>
<br>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.keypress=function(e) {
if(e.keyCode == 13) {
console.log('Enter');
}
}
});
</script>