jQuery添加删除选择框和按钮中的类
问题描述:
我有两个选择框和一些按钮作为后类别过滤器。看看我的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');
});
会有人请告诉我如何得到这个工作?
答
只需在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
$collection.find('li').removeClass('product-collection__selector--active');
编辑答案
不需要如上更换只需添加以下两个线路代码。并进行更改如下:
var $dropdown = $collection.find('.filterselect');
var $selectors = $collection.find('.product-collection__selector,.filterselect__selector');
与
$dropdown.change(function()
AND
$dropdown.removeClass('filterselect__selector--active');
答
的FIDDLE解决了背景色的问题,更换
$selectors.change(function()
AND
$selectors.removeClass('filterselect__selector--active');
。 Onchange事件适用于选择节点,不适用于选项。也没有太多的要求应用.each在集装箱股利。
var $selectors = $('select.filterselect');
您可以使用jQuery遍历节点,.parent,。家长,。孩子,.find方法来定位要修改基础上,选择框被更改过的数据最接近的容器。
希望这会有所帮助。
你想把背景应用到谁身上?你能解释更多吗? – Saurabh
@Saurabh当单击任何按钮或选择框时,我希望它将背景颜色更改为绿色,然后在单击其他任何按钮或选项时更改为其原始颜色。 – RedGiant