按ENTER键获取表格元素

时间:2016-12-27 10:59:21

标签: javascript jquery html angularjs

当我点击特定元素(即我表格的每一行)时,我得到了我的对象,但我想要enter上的那个元素。下面的代码会让你更清楚,

这是我的对象

var test = [{"name": "Ravi","age": 15}, {"name": "Shaul","age": 25}];

这是我的HTML表格

<table id="mymthelptable" ng-show="getTableValue" class="table table-bordered table-responsive table-hover add-lineheight table_scroll" arrow-selector>
    <thead>
        <tr>
            <th ng-repeat="(key, value) in test[0]">
            </th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="item in test  | filter: searchText" ng-dblclick="setElement(item);">
            <td ng-hide="columnToHide.indexOf(key) !== -1" ng-repeat="(key, value) in item">
                {{value}}
            </td>
        </tr>
    </tbody>
</table>

这是我的js 我写了一个指令

app.directive('arrowSelector', ['$document', function($document) {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            // This function fires on double click of each row element
            scope.setElement = function(element) {
                    console.log(element) // Here i get the particular object like {"name" : "Ravi","age" : 15} if i click on first row
                }
                // This function fires on press enter of each row element
            $document.bind('keydown', function(e) {
                if (e.which == 13) {
                    console.log(e) // Here i want the object {"name" : "Ravi","age" : 15} like the upper one  but i did not get that
                    alert("wait");
                }
            });
        }
    };
}]);

1 个答案:

答案 0 :(得分:0)

您可以使用ng-keydown而不是指令,并使用tab-index将焦点放在要输入的元素上,下面是一个工作片段

&#13;
&#13;
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script
	src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
</head>
<body>
	<table id="mymthelptable" class="" style="border: 1px solid black"
		ng-controller="MyCtrl">
		<thead>
			<tr>
				<th ng-repeat="(key, value) in test[0]"></th>
			</tr>
		</thead>

		<tbody>
			<tr ng-repeat="item in test  | filter: searchText"
				ng-dblclick="setElement(item);">
				<td ng-repeat="(key, value) in item"
					ng-keydown="onkeydown(item,$event)" tabindex="0">{{value}}</td>
			</tr>
		</tbody>
	</table>
	<script>
		var app = angular.module('myApp', []);

		app.controller('MyCtrl', [ '$scope', function($scope) {
			$scope.test = [ {
				"name" : "Ravi",
				"age" : 15
			}, {
				"name" : "Shaul",
				"age" : 25
			} ];
			$scope.setElement = function(element) {
				console.log(element)
			}
			$scope.onkeydown = function(item, $event) {
				console.log("get item " + item.name);
				console.log("get which" + $event.which)
				if ($event.which == 13) {
					alert("wait");
				}

			}
		} ]);
	</script>
</body>
</html>
&#13;
&#13;
&#13;