标签:des style blog http io color ar 使用 sp
最近做内推项目,虽然项目不算太大,还是遇到了一些代码组织的问题,说到底还是对整个项目的掌控力不够,为此乐帝专门在网络中搜集了一些jquery代码组织的文章并总结出两种方法来更好组织jquery代码。
一、回调函数
回调函数的定义:
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
回调是将一个函数作为变量,传入另外一个函数。前者将会在后者执行完成后执行。
上述简单的回调例子,说明函数的参数可以是一个函数,这也是jquery回调函数用法的基础了。
function hideSearchArea(callback) {
$(".search-area-container").hide();
var width = searchArea.width();
searchArea.animate({ "left": -width }, 400, function () {
if (callback) {
callback();
}
});
}
btnSearch.click(function () {
var keyWord = $('#keyWord').val();
var locId = $("#citySelect").val();
if (keyWord == oldSearchData.keyWord && locId == oldSearchData.locId) {
hideSearchArea();
return false;
}//老数据不返回数据
hideSearchArea(function () {
jobList.empty();
pageNum = 1;//清空page数
getInternalRecommendJobAdList(keyWord, locId);//加载搜索项
});//采用回调,省去了传参数的问题
});二、jquery代码组织要点
<ul id="myFeature">
<li>hi oop</li>
</ul>var myFeature = {
//首先类的实例属性用this.xxx形式定义,类属性用className.xxx形式定义
//以下各函数与配置对象都为类属性
// 初始化配置Jquery对象参数,并调用事件绑定设定函数
// 类内部,使用_this对对象进行替代,便于标示
init : function(settings) {
_this = myFeature;
_this.config = {
$items : $('#myFeature li'),
$container : $('<div class="container"></div>'),
};
$.extend(_this.config, settings || {});
_this.setup();
},
// 事件绑定设定函数,用于绑定事件,沟通jquery对象与响应事件
setup : function() {
var item = _this.config.$items;
item.each(_this.createContainer)
.click(_this.showItem);
},
//在li下创建div并设置数据
createContainer : function() {
var $i = $(this),
$c = _this.config.$container.clone()
.appendTo($i);
$i.data('container',"hello world");
},
showItem : function() {
_this.$currentItem = $(this);
_this.getContent();
},
getContent : function() {
var txt = _this.$currentItem
.data('container');
$(".container").html(txt);
},
};
$(function(){
myFeature.init();
}); var feature = (function() {
var $items = $('#myFeature li'), $container = $('<div class="container"></div>'), $currentItem,
init = function(settings){
setup();
},//初始化函数
setup= function() {
var item = $items.each(createContainer)
.click(showItem);
},//绑定函数
createContainer = function(idx) {
var $i = $(this),
$c = $container.clone()
.appendTo($i);
$i.data('container',"hello world");
},
showItem = function(){
$currentItem = $(this);
getContent();
},
getContent = function() {
var txt = $currentItem
.data('container');
$(".container").html(txt);
};
return {
init : init//对外接口
};
})();
feature.init();//初始化函数标签:des style blog http io color ar 使用 sp
原文地址:http://blog.csdn.net/yingyiledi/article/details/41116753