如何取消选择jQuery中的项目?

时间:2017-02-05 11:07:05

标签: javascript jquery html

我对jQuery有点问题。我对它很新,所以我将详细解释我在做什么。 我有几个h1通过jQuery填充连续数字。

<h1 class="number"><span></span></h1> *31

var date = 1;

$('.number').each(function() {
    $(this).find('span').html(date);
    date++;
});

我可以使用h1选择个人.addClass("selected")

$('.number').click(function() {
    $(this).toggleClass("selected");
});

问题是我可以选择多个元素。理想情况下,我可以选择一个项目,当我选择另一个项目时,前一个项目将失去“选中”类。我该怎么做?

3 个答案:

答案 0 :(得分:1)

你可以这样做:

$('.number').click(function() {
  $(this).toggleClass("selected")
         .siblings('.selected').removeClass("selected");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><style>h1{margin:0;padding:.5em;font-size:16px;font-family:Arial,Helvetica,sans-serif;border-bottom:1px solid #ddd;cursor:pointer;-webkit-transition:all .15s ease;-moz-transition:all .15s ease;transition:all .15s ease}h1:hover{background:#eee}.selected{background: #555!important; color: #fff}.selected:hover{background: #666!important;}</style> <h1 class="number"><span>1</span></h1><h1 class="number"><span>2</span></h1><h1 class="number"><span>3</span></h1><h1 class="number"><span>4</span></h1><h1 class="number"><span>5</span></h1><h1 class="number"><span>6</span></h1><h1 class="number"><span>7</span></h1><h1 class="number"><span>8</span></h1><h1 class="number"><span>9</span></h1><h1 class="number"><span>10</span></h1><h1 class="number"><span>11</span></h1><h1 class="number"><span>12</span></h1><h1 class="number"><span>13</span></h1><h1 class="number"><span>14</span></h1><h1 class="number"><span>15</span></h1><h1 class="number"><span>16</span></h1><h1 class="number"><span>17</span></h1><h1 class="number"><span>18</span></h1><h1 class="number"><span>19</span></h1><h1 class="number"><span>20</span></h1><h1 class="number"><span>21</span></h1><h1 class="number"><span>22</span></h1><h1 class="number"><span>23</span></h1><h1 class="number"><span>24</span></h1><h1 class="number"><span>25</span></h1><h1 class="number"><span>26</span></h1><h1 class="number"><span>27</span></h1><h1 class="number"><span>28</span></h1><h1 class="number"><span>29</span></h1><h1 class="number"><span>30</span></h1><h1 class="number"><span>31</span></h1>

答案 1 :(得分:0)

试试这个:

$('.number').click(function() {
    // select the .number elements that have the class .selected and remove it from them
    $('.number.selected').removeClass('selected');

    // add it to this one
    $(this).addClass("selected");
});

答案 2 :(得分:0)

首先从all中删除所选的类,然后添加它,点击它。

$('.number').click(function() {
   $('.number').removeClass("selected"):
   $(this).addClass("selected");
});