2014-02-14 44 views
0

我有两个选择框和一些按钮作为后类别过滤器。看看我的Fiidle。当我点击任何按钮或选择框时,我想添加背景颜色,并在点击另一个时将其删除。效果与此example中的 完全相同。jQuery添加删除选择框和按钮中的类

我想我必须在选择框中注册一个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'); 
}); 

会有人请告诉我如何得到这个工作?

+0

你想把背景应用到谁身上?你能解释更多吗? – Saurabh

+0

@Saurabh当单击任何按钮或选择框时,我希望它将背景颜色更改为绿色,然后在单击其他任何按钮或选项时更改为其原始颜色。 – RedGiant

回答

2

只需在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

0123取出活跃
$collection.find('li').removeClass('product-collection__selector--active'); 

Updated DEMO

编辑答案

不需要如上更换只需添加以下两个线路代码。并进行更改如下:

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

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

NEW UPDATED FIDDLE

+0

它很接近。当我在选择框中选择一个选项时,是否可以从我之前单击的按钮中删除类'product-collection__selector - active'? – RedGiant

+0

请检查我的更新答案。 –

+0

当从'var $ selectors'中删除'.product-collection__selector'时,按钮过滤器不再起作用。你如何让他们与选择框一起工作?为按钮创建一个新的变量? – RedGiant

1

FIDDLE解决了背景色的问题,更换

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

。 Onchange事件适用于选择节点,不适用于选项。也没有太多的要求应用.each在集装箱股利。

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

您可以使用jQuery遍历节点,.parent,。家长,。孩子,.find方法来定位要修改基础上,选择框被更改过的数据最接近的容器。

希望这会有所帮助。