我有两个来自不同上下文的单击函数 - 一个用jquery同位素过滤一些元素,另一个用无序列表模拟下拉功能。
下拉列表有效,但由于两个点击功能,我必须双击列表项以关闭下拉列表。
有人可以帮我将这两个点击功能合并为一个吗?
我有一个不错的小 jsfiddle 和预览脚本:
$(function(){
var $container = $('#container'),
filters = {};
$container.isotope({
itemSelector: '.item',
filter: '',
layoutMode: 'masonry',
animationEngine: 'css',
containerStyle: {
position: 'relative',
overflow: 'hidden'
},
animationOptions: {
duration: 2500,
easing: 'linear',
queue: false
}
});
////////// first click function: filter links
$('.filter a').click(function(){
var $this = $(this);
// don't proceed if already selected
if ( $this.hasClass('selected') ) {
return;
}
var $optionSet = $this.parents('.option-set');
// change selected class
$optionSet.find('.selected').removeClass('selected');
$this.addClass('selected');
// store filter value in object
// i.e. filters.color = 'red'
var group = $optionSet.attr('data-filter-group');
filters[ group ] = $this.attr('data-filter-value');
// convert object into array
var isoFilters = [];
for ( var prop in filters ) {
isoFilters.push( filters[ prop ] )
}
var selector = isoFilters.join('');
$container.isotope({ filter: selector });
return false;
});
////////// Second Click function for faux Dropdown (replace span)
function DropDown(el) {
this.dd = el;
this.placeholder = this.dd.children('span');
this.opts = this.dd.find('ul.dropdown > li');
this.val = '';
this.index = -1;
this.initEvents();
}
DropDown.prototype = {
initEvents : function() {
var obj = this;
obj.dd.on('click', function(event){
$(this).toggleClass('active');
return false;
});
obj.opts.on('click',function(){
var opt = $(this);
obj.val = opt.text();
obj.index = opt.index();
obj.placeholder.text(obj.val);
});
},
getValue : function() {
return this.val;
},
getIndex : function() {
return this.index;
}
}
$(function() {
var dd = new DropDown( $('#dd') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown').removeClass('active');
});
});
});
答案 0 :(得分:2)
您必须从return false;
事件处理程序中删除$('.filter a').click()
。 (working jsFiddle)
它正在削减所有其他代码的执行。我建议你改用.preventDefault()
之类的东西(我已经更新了jsFiddle以包含它)。
答案 1 :(得分:0)
您可以在第一个单击功能中切换.active类:
//...
////////// first click function: filter links
$('.filter a').click(function(){
$('.wrapper-dropdown').toggleClass('active'); // Added this!
var $this = $(this);
// don't proceed if already selected
if ( $this.hasClass('selected') ) {
return;
}
//...