gpt4 book ai didi

javascript - 选择/取消选择单元格时从数组中添加/删除项目

转载 作者:行者123 更新时间:2023-12-02 15:44:01 24 4
gpt4 key购买 nike

我有一个非常简单的日历(使用 Ionic/AngularJS),它使用一个虚构的月份,它只是一个包含数字 1-31 的表格。

我目前正在使用它,以便当用户按下单元格时,“selected”类将添加到选定的“td”中,并且“td”的内容将添加到数组中。

这似乎工作得很好,但是,如果我取消选择一个单元格,那么该项目将再次添加到“答案”数组中,所以现在我的数组中有重复项。

如何修改以下 fiddle 中的代码以选择/取消选择字段并相应地修改我的“答案”数组?

MyCtrl

function MyCtrl($scope) {
$scope.input = [];
$scope.input.answers = [];

$scope.bindCellValue = function(event) {
var elem = event;

if(elem.target.className == 'selected')
elem.target.className = '';
else
elem.target.className = 'selected';

$scope.input.answers.push(parseInt(elem.target.innerHTML));
console.log($scope.input.answers);
}
}

模板 (HTML)

<div ng-app>
<div ng-controller="MyCtrl">
<table class="calendar">
<thead>
<tr>
<th>M</th>
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
<th>S</th>
</tr>
</thead>
<tbody ng-click="bindCellValue($event)">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
<td>21</td>
</tr>
<tr>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
<td>28</td>
</tr>
<tr>
<td>29</td>
<td>30</td>
<td>31</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
</div>
</div>

http://jsfiddle.net/g8sxj6df/

最佳答案

您只需在推送之前检查数组即可。如果该元素存在,只需将其从数组中删除(如果需要)。这就是更新后的 Controller 的外观。

function MyCtrl($scope) {
$scope.input = [];
$scope.input.answers = [];

$scope.bindCellValue = function(event) {
var elem = event;

if(elem.target.className == 'selected')
elem.target.className = '';
else
elem.target.className = 'selected';
num = parseInt(elem.target.innerHTML);
if($scope.input.answers.indexOf(num) == -1){
$scope.input.answers.push(num);
}else{
$scope.input.answers.splice($scope.input.answers.indexOf(num),1);
}

console.log($scope.input.answers);
}
}

要查看它的实际工作情况,请在此处检查 fork 的 JSFiddle - http://jsfiddle.net/zqbL8nc0/

如果您有任何疑问/疑问,请告诉我。

关于javascript - 选择/取消选择单元格时从数组中添加/删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32370448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com