Jquery代码组织方法优化

关于jQuery的代码,以前都是直接取节点,绑事件一把梭,但是这样子会使代码很乱不方便维护。

今天介绍一个新的代码组织形式

实现看原代码

    $(function () {
        //切换bananer
        $('.bar-item').click(function () {
            $(this).attr('class', "bar-item bar-cur").siblings().attr('class', "bar-item")
            $(".banner a").eq($(this).attr("index")).fadeIn(1800).siblings().fadeOut();
        })
    })

原代码就是很简单的这样一个操作,这样看起来也没什么问题,但是当我们的页面有很多个DOM节点需要操作时,如果代码还是这样写就会显得很乱,下面进行代码组织优化

var index = {
    // 初始化
    init: function () {
        var me = this
        me.target()
        me.created()
        me.render()
    },

    // 相关DOM节点存储
    target: function () {
        var me = this;
        me.barItem = $('.bar-item') // banner切换按钮 
    },

    // 页面初始化数据获取
    created: function () {
        var me = this;
    },

    // 事件绑定
    render: function () {
        var me = this
        // 切换banner事件
        me.barItem.click(function () {
            $(this).attr('class', "bar-item bar-cur").siblings().attr('class', "bar-item")
            $(".banner a").eq($(this).attr("index")).fadeIn(1800).siblings().fadeOut();
        })
    }
}

$(function () {
    index.init();
});

这种写法大家应该都是不陌生发,防止了变量污染,而且集中管理变量、事件方便后期维护

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值