2015-07-02 75 views
1

我有這個投票片段,我想添加一個禁用的類到另一個按鈕比用戶按下。例如,如果用戶在id 1帖子上投票+,那麼 - 按鈕會得到一個禁用的類,但不是id 2。通過屬性查找最接近的元素

<span class="pull-right"> 
       <a href="javascript:void(0)" class="vote" data-id="1" data-type="up">+</a> 
       <span id="votes-1">0</span> 
       <a href="javascript:void(0)" class="vote" data-id="1" data-type="down">-</a> 
</span> 
<span class="pull-right"> 
       <a href="javascript:void(0)" class="vote" data-id="2" data-type="up">+</a> 
       <span id="votes-2">0</span> 
       <a href="javascript:void(0)" class="vote" data-id="2" data-type="down">-</a> 
</span> 

我已經試過幾件事情像.closest()。find()方法,但我不能使它發揮作用。

回答

3
  1. 遍歷到點擊的.vote元素的父級。
  2. 使用.not()this排除點擊的.vote元素。

$('.vote').click(function() { 
 
    var parent = $(this).parent(); 
 
    $(this).removeClass('disabled'); 
 
    parent.find('.vote').not(this).addClass('disabled'); 
 
});
.disabled { 
 
    background: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
 
<span class="pull-right"> 
 
       <a href="javascript:void(0)" class="vote" data-id="1" data-type="up">+</a> 
 
       <span id="votes-1">0</span> 
 
<a href="javascript:void(0)" class="vote" data-id="1" data-type="down">-</a> 
 
</span> 
 
<span class="pull-right"> 
 
       <a href="javascript:void(0)" class="vote" data-id="2" data-type="up">+</a> 
 
       <span id="votes-2">0</span> 
 
<a href="javascript:void(0)" class="vote" data-id="2" data-type="down">-</a> 
 
</span>

+0

打我吧:)沒有看到您的編輯! –

+0

謝謝,它的工作:) – Hunrik

+0

@Envex,很高興它幫助:) – AmmarCSE

2

您可以使用多種方法。

  1. 以下jQuery代碼是最短的一個。它需要所有的兄弟姐妹並用選擇器對它們進行過濾。陣列中唯一的項目將是另一個按鈕:

    $(".vote").click(function() 
    { 
        $(this).siblings(".vote").addClass("disabled");   
    }); 
    
  2. 您也可以這樣做。它正在通過屬性值全局搜索。如果您需要通過id屬性禁用文檔中的其他內容,這是一件好事。

    $(".vote").click(function() { 
        var id = $(this).data('id'); 
        $(".vote[data-id='" + id + "']").not(this).addClass("disabled"); 
    }); 
    
  3. 另一個選項是遍歷到父,通過選擇器和排除當前的元素。在內部,它與第一個幾乎相同。

    $(".vote").click(function() { 
        $(this).parent().find(".vote").not(this).addClass("disabled");   
    }); 
    

選擇其中一個最preferrable。

3
$('.vote').click(function() { 
    var parent = $(this).parent(); 
    $(this).removeClass('disabled'); 
    parent.find('.vote').not(this).addClass('disabled'); 
});