关于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();
});
这种写法大家应该都是不陌生发,防止了变量污染,而且集中管理变量、事件方便后期维护