簡體   English   中英

獲取 $(this) 元素的 html 並插入 $scope.variable

[英]Grab $(this) element's html and insert into $scope.variable

我試圖用.html()抓取buttons html 並插入$scope.player 該按鈕正在使用ng-click調用choosePlayer()函數,但它不起作用。

這是 codepen 鏈接: http ://codepen.io/theMugician/pen/ojJrRp

HTML

<body ng-app="ticTacToe" ng-controller="MainCtrl">

<div class="container">
  <div class="row">
    <div class="col-xs-12 text-center">
      <h1>TIC TAC TOE</h1>
    </div>
  </div>
</div>

<div id="wrapper" class="container text-center">
  <div class="row">
    <div ng-click="move(cell)" ng-repeat="cell in cells" class="col-xs-4 square text-center">
      {{cell.value}}
    </div>
  </div>

</div>
<div class="container">
  <div class="row text-center">
    <h1>CHOOSE A SHAPE</h1>
    <button ng-click="choosePlayer()" class="btn btn-red" id="choose-cross">✖</button>
    <button ng-click="choosePlayer()" class="btn btn-green" id="choose-circle">&#9711;</button>
  </div>
</div>
</body>

爪哇腳本

var app = angular.module("ticTacToe", []);
app.controller("MainCtrl", function($scope){
  var cell = $(".square");
  $scope.player = "";
  var cross = "×";
  var circle = "◯";

  $scope.choosePlayer = function(){
    $scope.player = $(this).html();
  }

  $scope.cells = [ { value: '' }, { value: '' }, { value: '' }, 
     { value: '' }, { value: '' }, { value: '' } ,
    { value: '' }, { value: '' }, { value: '' }  
  ];

  $scope.move = function(cell){
    cell.value = $scope.player;
  };

});

您可以在ng-click()指令中傳遞$event對象

<button ng-click="choosePlayer($event)" class="btn btn-red" id="choose-cross">✖</button>
<button ng-click="choosePlayer($event)" class="btn btn-green" id="choose-circle">&#9711;</button>

然后訪問event.currentTarget以獲取控制器中的元素:

更新示例

沒有 jQuery:

$scope.choosePlayer = function(e) {
  $scope.player = e.currentTarget.innerText;
}

使用 jQuery:

$scope.choosePlayer = function(e) {
  $scope.player = $(e.currentTarget).text();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM