Javascript计数功能的最大值&提交最多

时间:2017-12-15 23:10:37

标签: javascript angularjs function counter

我想将此计数功能限制为仅允许选择3个项目,并在选择3个项目后提交。我在HTML中使用ng-click="cuisine.selected = !cuisine.selected"

$scope.select_cuisine = function(cuisine_id){
  var count=0;
  for (let i=0; i<$scope.cuisines.length; i++) {
    if ($scope.cuisines[i].selected) count++;
  }
  return count;
}

有一种简单的方法吗?

3 个答案:

答案 0 :(得分:0)

您可以使用其他if语句来检查count。如果是count === 3,那么return

&#13;
&#13;
var cuisine = [true, false, false, true, false, true, false, false, true];

var countTilThree = function(cuisine) {
  var count = 0;

  for (let i = 0; i < cuisine.length; i++) {
    if (cuisine[i] === true)
      count++;
   
    if(count === 3)
      return count;
  }
  return count;
}

console.log(countTilThree(cuisine));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我会做这样的事情。创建一个存储选择的数组。在每个选项上,您可以检查它是否已被选中。如果不是,请确保未达到最大值,然后添加。如果该项已在数组中(已选中),请将其从数组中删除。这又将它的长度设置为1,这样你就可以添加另一个。

这是一个演示:

&#13;
&#13;
angular.module('app', []);

angular.module('app')
  .controller('Controller', function($scope) {

    $scope.selectedIds = [];
    $scope.selectCuisine = function(cuisine_id) {

      var idx = $scope.selectedIds.indexOf(cuisine_id);

      if (idx === -1) {
        // don't have the id, add operation

        if ($scope.selectedIds.length < 3) {
          // we're in range, do something with the selected ID
          $scope.selectedIds.push(cuisine_id);
        } else {
          // notify the user somehow
          console.warn('max selection reached');
        }
      } else {
        // already have the id, so we remove it
        $scope.selectedIds.splice(idx, 1);
      }
    }

  });
&#13;
<!doctype html>
<html ng-app="app">

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
  <script src="example.js"></script>
</head>

<body>

  <div ng-controller="Controller">

    <button ng-click="selectCuisine(1)">Select 1</button>
    <button ng-click="selectCuisine(2)">Select 2</button>
    <button ng-click="selectCuisine(3)">Select 3</button>
    <button ng-click="selectCuisine(4)">Select 4</button>

    <h4 ng-show="selectedIds.length === 3">No more! Remove one first!</h4>

    <h4>Selected IDS</h4> {{ selectedIds }}

  </div>
</body>

</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果当前所选项目的数量为3且未选择该项目,则最好的方式是禁用复选框。

每次用户选择项目时,请更新$ scope.count。

设置ng-enable ='item.selected ||计数&lt; 3'