簡體   English   中英

jQuery在選擇框和按鈕中添加刪除類

[英]jQuery add remove classes in select box and buttons

我有兩個選擇框和幾個按鈕作為帖子類別過濾器。 看看我的Fiidle 我想在單擊任何按鈕或選擇框時添加背景色,然后在單擊其他按鈕時將其刪除。 效果與本示例完全相同。

我想我必須在選擇框上注冊一個change事件。 但是,作為一個初學者,我所能想到的就是切碎這段代碼

$selectors.change(function() 
{
     var $selector = $(this);
     var cat = $selector.data('product-collection__category');
     $selectors.removeClass('product-collection__selector--active');
     $selector.addClass('product-collection__selector--active');
});

並把它變成這個無效的代碼

$selectors.change(function() 
{
     var $selector = $(this);
     var cat = $selector.find('option:selected').data('product-collection__category');
     $selectors.removeClass('filterselect__selector--active');
     $selector.addClass('filterselect__selector--active'); 
});

有人可以告訴我如何使它工作嗎?

只需在CSS下方添加效果即可。

.product-collection__selector:hover {
    background: green;
}
.product-collection__selector {
    -webkit-transition:background-color 0.3s ease-in;
    -moz-transition:background-color 0.3s ease-in;
    -o-transition:background-color 0.3s ease-in;
    transition:background-color 0.3s ease-in;
}  

JS變更

更換

var $dropdown = $collection.find('.filterselect');

 var $selectors = $collection.find('.product-collection__selector,.filterselect__selector');

var $selectors = $collection.find('.filterselect');  

在您的更改事件中添加以下代碼以從li刪除活動class

$collection.find('li').removeClass('product-collection__selector--active');

更新了演示

編輯答案

不需要替換上面的內容,只需在下面的兩行代碼中添加即可。 並進行如下更改:

var $dropdown = $collection.find('.filterselect');
var $selectors = $collection.find('.product-collection__selector,.filterselect__selector');  

更換

$selectors.change(function () 
AND
$selectors.removeClass('filterselect__selector--active');

$dropdown.change(function ()
AND
$dropdown.removeClass('filterselect__selector--active');

新更新的字段

FIDDLE解決了背景色問題。 Onchange事件在選擇節點上起作用,而不在選項上起作用。 同樣,對容器div應用.each也沒有太多要求。

var $selectors = $('select.filterselect');

您可以使用jQuery節點遍歷,.parent,.parents,.children,.find方法來基於更改后的選擇框找到您要在其中修改數據的最近容器。

希望這可以幫助。

暫無
暫無

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

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