首页 > 解决方案 > 在没有jQuery的表格行末尾附加一个元素?(使用 AngularJS)

问题描述

我有一个普通的 HTML 表,我需要在每一行的末尾附加一个按钮,该按钮将附加一个函数。我正在使用 AngularJS,所以我不想使用 jQuery 来添加它。有没有办法做到这一点?每次我尝试在行内添加一个 div 时,它都会将其删除。

编辑:添加了表格的外观

https://jsfiddle.net/vgck08zn/

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">name</th>
      <th scope="col">amount</th>
      <th scope="col">dob</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td>john</td>
      <td>$10.00</td>
      <td>03/02/2000</td>
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>bob</td>
      <td>$2.00</td>
      <td>02/01/02</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>will</td>
      <td>$200.00</td>
      <td>01/01/2003</td>
    </tr>
  </tbody>
</table>

我想要一个仅在您将鼠标悬停在一行上时才显示的按钮,并且该行的末尾

标签: htmlangularjs

解决方案


<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<style>
td{width:100px;}
th{font-weight:bold;}
button{width:100px;}
</style>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<table border=1 style="border-collapse:collapse;border:0;text-align: left;" ng-if="items.length >0">

	<tr>
		<th> id </th>
		<th> name </th>
		<th> price </th>
		<th> quantity </th>
	</tr>
	<tr ng-repeat="item in items" ng-mouseover="item.show_action = true" ng-mouseleave="item.show_action = false">
		<td>{{item.id}}</td>
		<td>{{item.name}}</td>
		<td>{{item.price}}</td>
		<td>{{item.quantity}}</td>
		<td ng-show="item.show_action" style="border:none;">
      <button ng-click="removeItem(item)">X - Delete
      </button> 
    </td>
	</tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.items = [];

    for (var i = 0; i < 5; i++) {	
        $scope.items.push({
          id:(i+1) ,
          name:("item "+i), 
          price :(Math.floor(Math.random() * 100)),
          show_action :false,
          quantity:(Math.floor(Math.random() * 1000))    
        });
     }       
    
    $scope.removeItem = function(item){
    for (var i = 0; i < $scope.items.length; i++) {
      if (item.id === $scope.items[i].id) {
          $scope.items.splice(i, 1);
        }
      }
    }
});
</script>

</body>
</html>


推荐阅读