javascript - 如何使用js增加onclick事件的积分?

标签 javascript html css angularjs ionic-framework

我正在构建一个测验,其中有两个选项可以回答问题,滑动(向右或向左)或单击(心形或划掉心形)选项。

我可以使用滑动功能并正确地制表分数,但我无法让点击事件运行用于计算答案是否正确的参数。

我的 HTML 看起来像这样:

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

  <title>Quiz</title>
    <link rel="stylesheet" href="css/style.css">
    <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
    <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
    <script src="http://code.ionicframework.com/collide/0.0.4/collide.js"></script>
    <script src="http://www.loringdodge.com/files/ionic.tdcards2.js"></script>
</head>

<body ng-app="starter" no-scroll>
    <ion-pane ng-controller="CardsCtrl" class="background-grey">
      <ion-header-bar class="bar-default">
        <h1 class="title">Quiz</h1>
      </ion-header-bar>

      <div class="td-title">
        <div class="row">
          <div class="col">Master: <span>{{ cards.master.length }}</span></div>
              <p style="color:blue;"><strong>Points</strong> : <span>{{points}}</span></p>
          <div class="col">Bands: <span>{{ cards.active.length }}</span></div>
          <div class="col">Discards: <span>{{ cards.discards.length }}</span></div>
        </div>
        <div class="row">
          <div class="col">Liked: <span>{{ cards.liked.length }}</span></div>
          <div class="col">Disliked: <span>{{ cards.disliked.length }}</span></div>
        </div>
      </div>

      <h2 id="family-zone">SWIPE RIGHT<br>FOR FAMILY</h2>
      <h2 id="not-family-zone">SWIPE LEFT<br>FOR NOT FAMILY</h2>


      <!-- *************************
        TD Cards
        - We start off with an ng-if so that the cards are not generated
          unless $scope.cards is not 'null'
      ************************* -->
      <div ng-if="cards.active">
        <td-cards>
          <td-card ng-repeat="card in cards.active" on-destroy="cardDestroyed($index)" on-swipe-left="cardSwipedLeft($index)" on-swipe-right="cardSwipedRight($index)">
            <div class="image" ng-controller="CardCtrl">
              <div class="no-text" ng-click="onClickTransitionOut(card)($index)" ng-click="onClickNotFamily(card)($index)"></div>
              <div class="yes-text" ng-click="onClickTransitionOut(card)($index)" ng-click="onClickFamily(card)($index)"></div>

              <!-- *************************
                Discard
                - The card is removed from the deck and a fly away animation is triggered.
                - onClickTransitionOut is found in ionic.tdcards.js
                - Animation can be customized by changing defaults
              ************************* -->

              <img ng-src="{{ card.image }}">
            </div>
          </td-card>
          <!-- *************************
            End Card
            - 'drag' is set to false. The user cannot drag it.
            - 'refreshCards()' reloads all cards that have NOT been discarded.
          ************************* -->
          <td-card id="end-card" drag="false">
          <h2 id="share">SHARE ON FACEBOOK</h2>
           <!--  <i class="icon ion-ios-refresh disable-user-behavior" ng-click="refreshCards()"></i> -->
          </td-card>
        </td-cards>
      </div>


    </ion-pane>
  </body>

我的 Javascript 目前看起来像这样:

 <script type="text/javascript">

        angular.module('starter', ['ionic', 'ionic.contrib.ui.tinderCards2'])


.config(function($stateProvider, $urlRouterProvider) {

})

.directive('noScroll', function($document) {

  return {
    restrict: 'A',
    link: function($scope, $element, $attr) {

      $document.on('touchmove', function(e) {
        e.preventDefault();
      });
    }
  }
})

.controller('CardsCtrl', function($scope, TDCardDelegate, $timeout) {

  var cardTypes = [

  { 
    "image": 'http://classicsdujour.com/wp2015/wp-content/uploads/2015/01/Van-Halen-Deluxe-Cover.jpg',
    "question" : "Q: This question is true",
    "valid"    : 1, // indicates the correct array number, use 0, 1...
    "buttons"  : ["False", "True"],
    "answers"  : [ "The correct answer is True"]  
  },
  {
    "image": 'https://www.dustygroove.com/images/products/j/jackson5~~~_abc180gra_101b.jpg',
    "question" : "Q: This answer to this question is true",
    "valid"    : 1,
    "buttons"  : ["False", "True"],
    "answers"  : [ "The correct answer is True"] 
  },
  {
    "image": 'https://fanart.tv/fanart/music/9beb62b2-88db-4cea-801e-162cd344ee53/albumcover/solid-gold-hits-504adea20593c.jpg',
    "question" : "Q: This question is false",
    "valid"    : 0, 
    "buttons"  : ["False", "True"],
   "answers"  : [ "The correct answer is False"] 
  },
    {
    "image": 'http://cdn.therockcorner.com/artists/k/kings-of-leon/albums/youth-and-young-manhood-5.jpg',
    "question" : "Q: The answer to this question is truuueee",
    "valid"    : 1,
    "buttons"  : ["False", "True"],
    "answers"  : [ "The correct answer is True"] 
  },
    {
    "image": 'https://analogkidblog.files.wordpress.com/2015/06/the-family-320-kbps.png',
    "question" : "Q: False is the answer here",
    "valid"    : 0,
    "buttons"  : ["False", "True"],
    "answers"  : [ "The correct answer is false"] 
  },
    {
    "image": 'https://upload.wikimedia.org/wikipedia/en/1/1c/SoundsSilence.jpg',
    "question" : "Q: This questions is false",
    "valid"    : 0,
    "buttons"  : ["False", "True"],
    "answers"  : [ "The correct answer is False"] 
  },
    {
    "image": 'http://static1.squarespace.com/static/5073209bc4aa6253939f5db3/t/5715299c40261d3e0a616695/1461004706936/?format=500w',
    "question" : "Q: True True Truueee",
    "valid"    : 1,
    "buttons"  : ["False", "True"],
    "answers"  : [ "The correct answer is True"] 
  },
    {
    "image": 'https://upload.wikimedia.org/wikipedia/en/a/ae/Daft_Punk_-_Discovery.jpg',
    "question" : "Q: This one is indeed false",
    "valid"    : 0,
    "buttons"  : ["False", "True"],
    "answers"  : [ "The correct answer is False"] 
  },
      {
    "image": 'http://66.media.tumblr.com/tumblr_lidp3btJqJ1qzk6vno1_1280.jpg',
    "question" : "Q:  Ahaaaa a true question",
    "valid"    : 1,
    "buttons"  : ["False", "True"],
    "answers"  : [ "The correct answer is True"] 
  },
    {
    "image": 'https://upload.wikimedia.org/wikipedia/en/2/20/Arcticmonkeys-humbug.jpg',
    "question" : "Q: Another false statement",
    "valid"    : 0,
    "buttons"  : ["False", "True"],
    "answers"  : [ "The correct answer is False"] 
  },
      //{
    //"question" : "Game over, check your score below.",

  //}

];

var qc        = 0, // Current Question counter
    points    = 0, // Current points
    validIdx = cardTypes.valid,
    $points   = ("p>span");


  $scope.cards = {
    master: Array.prototype.slice.call(cardTypes, 0),
    active: Array.prototype.slice.call(cardTypes, 0),
    discards: [],
    liked: [],
    disliked: []

  }

  $scope.points = 0;

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

  $scope.addCard = function() {
    var newCard = cardTypes[0];
    $scope.cards.active.push(angular.extend({}, newCard));
  }

  $scope.refreshCards = function() {
    // Set $scope.cards to null so that directive reloads
    $scope.cards.active = null;
    $timeout(function() {
      $scope.cards.active = Array.prototype.slice.call($scope.cards.master, 0);
    });
    $scope.points = 0;
  }

  $scope.$on('removeCard', function(event, element, card) {
    var discarded = $scope.cards.master.splice($scope.cards.master.indexOf(card), 1);
    $scope.cards.discards.push(discarded);
  });

  $scope.cardSwipedLeft = function(index) {
    console.log('LEFT SWIPE');
    var card = $scope.cards.active[index];
    $scope.cards.disliked.push(card);

    var givenAnswer = 0,
    correctAnswer = card.valid;  
  if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');            
  } else {
    console.log('incorrect!!!!');                       
  }
//increment the points variable if the answer is correct:

if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');
    $scope.points++;             
} 
  };

  $scope.cardSwipedRight = function(index) {
    console.log('RIGHT SWIPE');
    var card = $scope.cards.active[index];
    $scope.cards.liked.push(card);

   var givenAnswer = 1,
    correctAnswer = card.valid;  
  if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');            
  } else {
    console.log('incorrect!!!!');                       
  }
//increment the points variable if the answer is correct:
if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');
    $scope.points++;             
} 

  };

  $scope.onClickNotFamily = function(index) {
    console.log('LEFT CLICK');

    var givenAnswer = 0,
    correctAnswer = card.valid;  
    if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');            
    } else {
    console.log('incorrect!!!!');                       
    }
    //increment the points variable if the answer is correct:

    if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');
    $scope.points++;             
    } 

  };

  $scope.onClickFamily = function(index) {
    console.log('RIGHT CLICK');
    var card = $scope.cards.active[index];
    $scope.cards.liked.push(card);

   var givenAnswer = 1,
    correctAnswer = card.valid;  
  if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');            
  } else {
    console.log('incorrect!!!!');                       
  }
//increment the points variable if the answer is correct:
if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');
    $scope.points++;             
} 

  };


})




.controller('CardCtrl', function($scope, TDCardDelegate) {

});





        </script>

我只想让点击事件运行参数以确定答案是否正确。

例如,当用户向右滑动时运行此参数的当前脚本片段如下所示:

$scope.cardSwipedRight = function(index) {
    console.log('RIGHT SWIPE');
    var card = $scope.cards.active[index];
    $scope.cards.liked.push(card);

   var givenAnswer = 1,
    correctAnswer = card.valid;  
  if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');            
  } else {
    console.log('incorrect!!!!');                       
  }
//increment the points variable if the answer is correct:
if (givenAnswer === correctAnswer) {
    console.log('correct!!!!');
    $scope.points++;             
} 

  };

最佳答案

来自HTML spec :

When the user agent leaves the attribute name state (and before emitting the tag token, if appropriate), the complete attribute's name must be compared to the other attributes on the same token; if there is already an attribute on the token with the exact same name, then this is a parse error and the new attribute must be removed from the token.

意思是,当你写的时候:

<div class="no-text" ng-click="onClickTransitionOut(card)($index)" ng-click="onClickNotFamily(card)($index)"></div>

第一个ng-click属性 ( onClickTransitionOut... ) 被分配,第二个 ( onClickNotFamily ) 被丢弃,因为 ng-click 已经有值了.因此,只有第一个函数会在您单击时运行。

这里有两个选项可以解决这个问题,以便运行两个函数:

  • 重构您的代码,以便有一个函数可以绑定(bind)到 ng-click .我建议这样做,因为您的 JS 似乎在点击和滑动处理程序之间有一些复制/粘贴代码。

  • 合并ng-click属性ng-click="function1(); function2()" (如 this post 中所示)。

希望对您有所帮助!我不是 Angular 专家,所以可能还有其他我没有注意到的问题。

关于javascript - 如何使用js增加onclick事件的积分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39334370/

相关文章:

javascript - asp.net - 从弹出窗口显示弹出窗口

javascript - Ruby on Rails 和 Javascript

html - 尽管 URL 正确,但仍继续获取 "Failed to decode downloaded font"

javascript - 正则表达式中的重音符号有什么用?

javascript - 无法进行本地开发,错误为 : No 'Access-Control-Allow-Origin' header is present on the requested resource

javascript - 将文件放入区域 - 样式

php - 在 Laravel 中应用 Bootstrap 后页面出现盒装外观

jquery - Css 箭头进度条

JavaScript/CSS : normalize all element stylings on a page?

javascript - 如何在动画元素 onScroll 时获得准确的滚动位置