【问题标题】:How to make this JS to show next card instead of random cards?如何让这个 JS 显示下一张卡片而不是随机卡片?
【发布时间】:2019-08-21 18:54:51
【问题描述】:

我正在开发一个使用 HTML、CSS 和 JS 的刷卡项目。

我从 codepen 获取了这个 JS 代码并实现了它,但问题是卡片是随机的。如何使其按顺序排列(不重复)?

angular.module('starter', ['ionic', 'ionic.contrib.ui.cards'])
  .directive('noScroll', function($document) {
    return {
      restrict: 'A',
      link: function($scope, $element, $attr) {
        $document.on('touchmove', function(e) {
          e.preventDefault();
        });
      }
    }
  })

  .controller('CardsCtrl', function($scope, $ionicSwipeCardDelegate) {
    var cardTypes = [
      {title: '1'},
      {title: '2'},
      {title: '3'},
      {title: '4'},
      {title: '5'}
    ];

    $scope.cards = Array.prototype.slice.call(cardTypes, 0, 0);

    $scope.cardSwiped = function(index) {
      $scope.addCard();
    };

    $scope.cardDestroyed = function(index) {
      $scope.cards.splice(index, 1);
    };

    $scope.addCard = function() {
      var newCard = cardTypes[
        Math.floor(Math.random() * cardTypes.length)
      ];
      newCard.id = Math.random();
      $scope.cards.push(angular.extend({}, newCard));
    }
  })

  .controller('CardCtrl', function($scope, $ionicSwipeCardDelegate) {
    $scope.goAway = function() {
      var card = $ionicSwipeCardDelegate.getSwipeableCard($scope);
      card.swipe();
    };
  });

【问题讨论】:

    标签: javascript jquery html css angularjs


    【解决方案1】:

    我会更改以下内容:

    $scope.cards = Array.prototype.slice.call(cardTypes, 0, 0);
    

    替换为:

    $scope.cards = cardTypes; // this keeps the series ordered as is defined
    

    你可能想.reverse()cardTypes 所以数组中的第一项是第一张卡片(卡片实际上是从数组中弹出的,所以如果你不反转它,最后一项将是第一张卡片):

    $scope.cards = cardTypes.reverse(); // reverse the array
    

    然后似乎每次刷卡后都会随机添加新卡:

    $scope.cardSwiped = function(index) {
      $scope.addCard();
    };
    

    也许你可以评论整个事情,或者如果它破坏了应用程序,就只评论$scope.addCard()

    【讨论】:

    • 好吧,那我可能不明白你的问题,我已经尝试过你提供的 codepen,它按预期工作。 (根据我对您想要实现的目标的理解)。
    • 您想将卡片显示为一系列并按照定义的顺序显示吗?然后您是希望系列在到达最后一张牌后结束,还是要重复系列?
    • 这里是forked codepen
    • 不客气,另一个版本基于@DMishra 的回答,可能更简洁:codepen。您应该改用它,以便第一个“向下滑动以显示新卡片”卡片显示在开头而不是结尾
    【解决方案2】:

    问题在于您的$scope.addCard 在获得一张新卡时,您正在使用 Math.Random

    正确方法-

        var cardCount = -1;//    
        $scope.addCard = function () {
            if (cardCount < cardTypes.length - 2) {
                cardCount++;//get the next card
            }
            else {
                alert("Reached last card");//last card reached
            }
            var newCard = cardTypes[cardCount];
            newCard.id = cardCount;
            $scope.cards.push(angular.extend({}, newCard));
        }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多