给菜单加个优雅的unselect事件

先上图,说场景

假设默认选中的是item1,我现在选中item3了,有时候需要对item1做一些别的处理。常见的做法是,切换选中状态前找到当前选中(item1),或者每次选中后选中的项记录在中间变量。

这样处理没任何问题,不过心理总有点怪怪的,最好代码分离,就像这样:

$(this).unselect(fn_unselect).select(fn_select),具体代码是这样的:

$(function ()
        {
            $.$ul('#menu').children().each(function ()
            {
               
                $(this).unselect(function ()
                {
                    $(this).removeClass('selected');

                }).select(function ()
                {
            $(this).addClass('selected')
          }); 
        });
      });

用到的扩展函数:

 $.fn.extend({
            unselect: function (callback)
            {
                //this指unselect的项
                if (this[0].tagName === 'LI' && typeof callback === 'function')
                {
                    this.data('unselect', callback);
                    return this;
                }
            },
            select: function (callback)
            {
                //this指select的项
                if (this[0].tagName === 'LI' && typeof callback === 'function')
                {
                    this.data('select', callback);
                    return this;
                }
            }
        });
        $.extend({
            $ul: function (selector)
            {
                var res = $(selector);
                if (res[0].tagName !== 'UL') return undefined;                
                res.children().each(function ()
                {
                    //实际上这应该是clickAfter事件,此处用setTimeout(fn,delay);代替。即使不用此函数也会先于自定义的click事件
                    $(this).live('click', function ()
                    {
              var that = this;
                        var clickAfter=function ()
                        {
                            //处理unselect
                            var unselecting =  $(that).siblings('.selected');
                            unselecting.data('unselect').call(unselecting);

                            //处理select
                            var selecting=$(that)
                            selecting.data('select').call(selecting);

                        };
                        setTimeout(clickAfter, 1);//确保在click后执行
                    });
                });
                return res;
            }
        });

 

posted @ 2014-09-23 15:49  二师弟tl  阅读(511)  评论(0)    收藏  举报