好的JS应该具备什么特性
1 功能要具备
2 模块化,类似,有关联的代码要写到一起,适当的封装
3 适当提升复用度
效果图和对应的JS
Home.js
$(function(){ jQuery.urlParam = function(name){ var result = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]; return decodeURIComponent(result);} //$(".loading").show(); // 三种搜索类型各有标签为后面搜索页分的分类和分页做标识 // home页两种 头部一种 localStorage.stype=1 // 底部商品分类一种 localStorage.stype=2 // search.html 头部搜索一种 localStorage.stype=3 var _shop = { nextPageNumb:1, // 当前页标识 totalCount:0, // 总页数 pricSort:0, // 价格降序和升序的标识 flag:true, fsfalse:0, // 0 非假一罚十商家 1 是假一罚十商家 rzfalse:0, // 是否认证商家 0 未认证 1 已经认证 labelNumber:1, // 分页 哪个分类下的标识 1综合 2销量 3价格 // 商家信息 merchantsInfo:function(){ $.ajax({ url: "http://enterprise.qbao.com/merchant/shop/qry/getShopFrontPageInfo.html?display=1", type: "POST", contentType: "application/x-www-form-urlencoded; charset=utf-8", data: {"shopUserId":3896188}, success: function(data, status, jqXHR) { if(data && data.success == true) { var _data = data.data; _shop.fsfalse = _data.falseOnePenaltyTen; // 1 是参与假一罚十 _shop.rzfalse = _data.certifyType; // 0 未认证 1已经认证 // 商家信息内容绑定 _shop.merInfoData(_data); } else { _shop.prompt("请求错误!"); } }, error: function(){ _shop.prompt("请求错误!"); } }); }, // 商家信息内容绑定 merInfoData:function(_data){ if(_data.merchantType == 2){ // 商家类型 2企业商家 $(".certi").removeClass("hide"); }; $(".shopDetail").css("background-image",'url('+ _data.cover +')'); $(".shopDetail .logo img").attr("src", _data.logo); $(".saleNumber").html(_data.goodsNumberOnSale); // 在售产品数 $(".allNumber").html('(' + _data.goodsNumberOnSale + ')'); // 全部产品数 $(".newNumber").html('(' + _data.goodsNumberNewStyle + ')'); // 新款商品数 $(".shopTitle").html(_data.shopName); // 商家名称 $(".praise").html(_data.thumbsCount); // 点赞数 var userId = _data.userId; $(".shopDetail a").attr("href","shopInfo.html?userId=" + userId ); // banner显示 var bannerfalse = _data.displayBanners; if(bannerfalse.length>=1){ $(".box_swipe").show(); var liHtml = '', olHtml = ''; for(var i=0; i<bannerfalse.length; i++){ liHtml += '<li><a href=http://m.qbao.com/store/product.htm?productId='+ bannerfalse[0].goodsId +'><img src="' + bannerfalse[0].imgPath + '"></a></li>'; olHtml += '<li class="border_radus"></li>' } $(".box_swipe ul").append(liHtml); $(".box_swipe ol").append(olHtml); $(".box_swipe .img_1").hide(); $(".box_swipe ol li:eq(0)").addClass("on"); }else{ $(".box_swipe").hide(); } //初始化banner new Swipe(document.getElementById('banner_box'), { speed: 500, auto: 3000, callback: function () { var lis = $(this.element).next("ol").children(); lis.removeClass("on").eq(this.index).addClass("on"); } }) }, // 两个tab的切换 tab:function(ctn){ var li = ctn.find("li"); li.click(function(){ var id = $(this).data("id"); _shop.labelNumber = $(this).data("num"); $(this).siblings("li").removeClass("active"); $(this).addClass("active"); $("." + id).siblings().hide(); $("." + id).show(); $(".cfix").removeClass("fixed"); // 上新内容展示 if(id == "cnew"){ if($(".cnew li").length == 0){ _shop.tabNewData(id); } } // 综合和销量分别调用接口 // 第一次单击重新加载 否则 就隐藏显示即可 if(id == "ch"){ //综合 2 if($(".ch li").length == 0){ _shop.tabAllData('',2,1,1,"ch"); } }else if(id == "sales"){ //销量 0 if($(".sales li").length == 0){ _shop.tabAllData('',0,1,1,"sales"); } } // 价格图标转换和数据降和升序处理 if($(this).hasClass("active") && $(this).hasClass("pric")){ var liem = $(this).children("em"); liem.removeClass("default").addClass("arrowDown").toggleClass("arrowUp"); if($(this).find("em").hasClass("arrowUp")){ _shop.pricSort = 1; _shop.tabAllData('',1,0,1,"_pric"); // 升序 }else{ _shop.pricSort = 0; _shop.tabAllData('',1,1,1,"_pric"); // 降序 } }else{ $(".pric").children("em").addClass("default").removeClass("arrowDown arrowUp"); } }); }, // tab 全部 接口调用 tabAllData:function(ky,st,or,crt,cn){ $.ajax({ url: 'http://enterprise.qbao.com/merchant/shop/qry/searchProducts.html?shopUserId=1779040&keyword='+ ky +'&sortBy='+ st +'&orderBy='+ or +'¤tPage='+ crt, type: "POST", contentType: "application/x-www-form-urlencoded; charset=utf-8", success: function(data, status, jqXHR) { if(data && data.success == true) { _shop.nextPageNumb = data.data.nextPageIndex; $('.'+ cn +'').find(".initloading").addClass("hide"); _shop.totalCount = data.data.totalCount; _shop.allProductsCtn(data.data,cn); } else { $('.'+ cn +'').find(".initloading").addClass("hide"); _shop.prompt("请求错误!"); } }, error: function(){ $('.'+ cn +'').find(".initloading").addClass("hide"); _shop.prompt("请求错误!"); } }); }, // tab 上新 接口调用 tabNewData:function(cnew){ $.ajax({ url: "http://enterprise.qbao.com/merchant/shop/qry/getNewProducts.html?shopUserId=1779040", type: "POST", contentType: "application/x-www-form-urlencoded; charset=utf-8", data: {}, success: function(data, status, jqXHR) { if(data && data.success == true) { _shop.nextPageNumb = data.data.nextPageIndex; $(".cnew .nohtml").addClass("hide"); $(".cnew").find(".initloading").addClass("hide"); _shop.allProductsCtn(data.data,cnew); } else { $(".cnew").find(".initloading").addClass("hide"); _shop.prompt("请求错误!"); $(".cnew .nohtml").removeClass("hide"); } }, error: function(){ $(".cnew").find(".initloading").addClass("hide"); _shop.prompt("请求错误!"); $(".cnew .nohtml").removeClass("hide"); } }); }, // 商品的加载 allProductsCtn:function(_data,cn){ var products = _data.products, liHtml = ''; for(var p=0; p < products.length; p++){ liHtml += '<li data-id='+ products[p].id +'>'+ '<a href=http://m.qbao.com/store/product.htm?productId='+ products[p].id +'>'+ ' <img src="'+ products[p].mainImg+'"/>'+ ' <div class="infoText borderTop">'+ ' <p class="text_overflow name clearfix">'+ products[p].spuName; liHtml += (_shop.rzfalse == 1 ? '<em class="quan"></em>':''); liHtml +='</p>'+ ' <p class="clearfix pric">'+ ' <span class="left">'+ ' <em class="bao backionic"></em>'+ ' <span class="font_14">'+ products[p].viewPrice +'</span>'+ ' </span>'+ ' <span class="right grey">已售'+ products[p].salesNumAggregated +'</span>'+ ' </p>'; liHtml += (_shop.fsfalse == 1?'<p class="grey"><em class="penalty backionic"></em>假一罚十</p>':''); liHtml += ' </div>'+' </a>'+ '</li>'; } if(cn == "_pric"){ $(".tabCtn").find('.'+ cn +'').children("li").remove(); $("_pric .nohtml").addClass("hide"); $(".tabCtn").find('.'+ cn +'').append(liHtml); _shop.nextPageNumb ++ ; _shop.flag = true; }else{ $(".tabllctn").find('.'+ cn +'').append(liHtml); _shop.flag = true; } }, // 滚动分页 nextPage:function(){ switch(_shop.labelNumber){ case 1: noData('',2,1, _shop.nextPageNumb ,"ch"); // 综合 break; case 2: noData('',0,1, _shop.nextPageNumb ,"sales"); // 销量 break; case 3: // 价格 if(_shop.pricSort == 1){ noData('',1,0, _shop.nextPageNumb ,"_pric"); // 升序 }else{ noData('',1,1, _shop.nextPageNumb ,"_pric"); // 降序 } break; } // 判断是否还有数据 function noData(a,b,c,d,e){ if( _shop.nextPageIndex == ""){ alert("此处没有更多商品"); $(".moreloading").html("此处没有更多商品"); }else{ _shop.tabAllData(a,b,c,d,e); } }; }, // 顶部搜索 sureClick:function(){ // 初始化时 如果有值自动变红 inct(); // 搜索框 搜索图标的显示和隐藏 $('.headerSearch').bind('input onpropertychange', function() { inct(); }); // 公用函数 function inct(){ var hl = $('.headerSearch input').val(), hsi = $(".headerSearch .searchImg"), hs = $('.headerSearch input'); if(hl.length>0){ hsi.hide(); $(".headerSearch .sure").addClass("red"); hs.css("text-indent","0"); }else{ hsi.show(); $(".headerSearch .sure").removeClass("red"); hs.css("text-indent",".4rem"); }; } // 单击确定按钮跳转页面 带输入框参数 $(".headerSearch .sure").click(function(){ var _inputVal = $(this).prev("input").val(); if(_inputVal.length>0){ // 跳转页面带参数 location.href = "search.html?keyword=" + _inputVal; }else{ _shop.prompt("请输入关键字"); }; }); }, // 显示标签内容 labelDate:function(){ $(".stype").click(function(){ if($(".typeLi li").length == 0){ $.ajax({ url: "http://enterprise.qbao.com/merchant/shop/qry/getProductsCategory.html?shopUserId=8343192", type: "POST", contentType: "application/x-www-form-urlencoded; charset=utf-8", data: {}, success: function(data, status, jqXHR) { if(data && data.success == true) { var _data = data.data; if(_data.length == 0){ _shop.prompt("没有更多分类标签"); }else{ // 添加内容 _shop.labelCtn(_data); } } else { _shop.prompt("没有更多分类标签"); console.log("请求错误!"); } }, error: function(){ _shop.prompt("没有更多分类标签"); console.log("请求错误!"); } }); }else{ // 有数据时 显示样式 _shop.labelStyle(); }; }); }, // 有数据时 显示样式 labelStyle:function(){ $(".typeLi ul").css("max-height",((document.documentElement.clientHeight)/100 - 1) + "rem"); $("body").css("overflow","hidden"); $(".typeLi").slideDown(); $(".close").click(function(){ $(".typeLi").slideUp(); $("body").css("overflow",""); }); }, // 商品分类 点击底部弹出分类标签 单击跳转搜索页 设置搜索的类型 labelCtn:function(_data){ var liHtml = ""; for(var i=0; i<_data.length; i++){ liHtml += '<li><a href=search.html?keyword='+ _data[i].labelName +'>'+ _data[i].labelName +'</a></li>' } $(".typeLi ul").append(liHtml); // 有数据时 显示样式 _shop.labelStyle(); }, // 错误提示框 prompt:function(text){ $("body").append('<div class="promptCover">'+ text +'</div>'); var width = $(".promptCover").width(); $(".promptCover").css("margin-left",-(width/2)/100+"rem").fadeIn("slow"); setTimeout(function(){ $(".promptCover").fadeOut("slow").remove(); },10000); }, // 初始化加载的函数 init:function(){ _shop.tab($(".tabTop")); _shop.tab($(".tabBot")); _shop.sureClick(); _shop.labelDate(); _shop.merchantsInfo(); _shop.tabAllData('',2,1,1,"ch"); }, } _shop.init(); window.addEventListener("scroll",function() { var height = document.documentElement.clientHeight, scrollTop = document.body.scrollTop, allHeight = document.documentElement.scrollHeight; if(_shop.flag){ if(window.scrollY+$(window).height()>$(".shopbox").height()){ // 滚动分页 _shop.nextPage(); _shop.flag = false; }else{ $(".loadingmore").hide(); } }; // 全部选项卡下 标题浮动 var _top = $(".shopTab")[0].offsetTop; if(scrollTop >= _top){ $(".cfix").addClass("fixed"); $(".ted").show(); }else{ $(".cfix").removeClass("fixed"); $(".ted").hide(); }; }); });
Info.js
$(function(){ jQuery.urlParam = function(name){ var result = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]; return decodeURIComponent(result);} var info = { fsfalse:0, // 0 非假一罚十商家 1 是假一罚十商家 rzfalse:0, // 是否认证商家 0 未认证 1 已经认证 //userId:$.urlParam("userId"), userId:8343192, inData:function(){ $.ajax({ url: "http://enterprise.qbao.com/merchant/shop/qry/getShopDetail.html?shopUserId=" + info.userId, type: "POST", contentType: "application/x-www-form-urlencoded; charset=utf-8", data: {}, success: function(data, status, jqXHR) { if(data && data.success == true) { info.inHtml(data.data); }else{ info.prompt("请求错误!"); } }, error: function(){ info.prompt("请求错误!"); } }); }, // 数据获取 inHtml:function(_data){ info.fsfalse = _data.falseOnePenaltyTen; info.rzfalse = _data.certifyType; $(".shopInfo .logo img").attr("src", _data.logo); // 商家logo $(".detail .shopTitle, .info .name").html(_data.shopName); // 商家名称 $(".detail .zs").html(_data.productsTotalCount); // 在售产品数 $(".detail .praise").html(_data.thumbsCount); // 点赞数 $(".info .time").html(_data.openTime); if(info.fsfalse == 1){ // 判断是否参加假一罚十 $(".service").removeClass("hide"); }; if(_data.merchantType == 2){ // 商家类型 2企业商家 $(".merchantType").html("企业商家"); $(".qymerchant").removeClass("hide"); }else{ $(".merchantType").html("个人商家"); }; $(".qymerchant .zch").html(_data.compantMerchantRegisterInfo.companyName); // 营业执照 $(".qymerchant .zh").html(_data.compantMerchantRegisterInfo.businessLicenseNumber); // 登记证号 $(".qymerchant .ytime").html(_data.compantMerchantRegisterInfo.businessStartTime); // 营业期限 $(".qymerchant .fzr").html(_data.compantMerchantRegisterInfo.principalName); // 店铺负责人 $(".qymerchant .ctype").html(_data.compantMerchantRegisterInfo.companyType); // 公司类型 }, // 错误提示框 prompt:function(text){ $("body").append('<div class="promptCover">'+ text +'</div>'); var width = $(".promptCover").width(); $(".promptCover").css("margin-left",-(width/2)+"px").fadeIn("slow"); setTimeout(function(){ $(".promptCover").fadeOut("slow").remove(); },10000); }, } // 初始化 info.inData(); // 二维码显示 $(".codeImg").click(function(){ $(".popupCover, .popup").show(); $(".popup .close").click(function(){ $(".popupCover, .popup").hide(); }) }) })
search.js
扫描二维码关注公众号,回复:
343144 查看本文章
$(function(){ // $(".loading").show(); jQuery.urlParam = function(name){ var result = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]; return decodeURIComponent(result);} var main = { keyWord: $.urlParam("keyword"), // 关键词 nextPageNumb:1, // 当前页标识 totalCount:0, // 总页数 pricSort:0, // 价格降序和升序的标识 //flag:true, fsfalse:0, // 0 非假一罚十商家 1 是假一罚十商家 rzfalse:0, // 是否认证商家 0 未认证 1 已经认证 labelNumber:1, // 分页 哪个分类下的标识 1综合 2销量 3价格 _search:function(){ $('.headerSearch').bind('input onpropertychange', function() { var hl = $('.headerSearch input').val(); if(hl.length>0){ $(".headerSearch .clear").show(); $(".headerSearch .text").html("确定").addClass("red"); }else{ $(".headerSearch .clear").hide(); $(".headerSearch .text").html("取消").removeClass("red"); } }); // 输入框清除 $('.headerSearch .clear').click(function(){ $('.headerSearch input').val(""); $(".headerSearch .text").html("取消").removeClass("red"); }); $(".headerSearch .text").click(function(){ if($(this).html() == "取消"){ history.go(-1); }else{ main.keyWord = $('.headerSearch input').val(); } }); }, // tab:function(){ var tabli = $(".tabli"), li = $(".tabli li"), tabul = $(".tabul"); li.click(function(){ $(this).siblings("li").removeClass("active"); $(this).addClass("active"); var id = $(this).data("id"); $("." + id).siblings().hide(); $("." + id).show(); if(id == "ch"){ if($(".ch li").length == 0){ main.tabAllData(main.keyWord,2,1,1,"ch"); } }else if(id = "sales"){ if($(".sales li").length == 0){ main.tabAllData(main.keyWord,0,1,1,"sales"); } } if($(this).hasClass("active") && $(this).hasClass("pric")){ var liem = $(this).children("em"); liem.removeClass("default").addClass("arrowDown").toggleClass("arrowUp"); if($(this).find("em").hasClass("arrowUp")){ main.pricSort = 1; main.tabAllData(main.keyWord,1,0,1,"_pric"); // 升序 }else{ main.pricSort = 0; main.tabAllData(main.keyWord,1,1,1,"_pric"); // 降序 } }else{ $(".pric").children("em").addClass("default").removeClass("arrowDown arrowUp"); } }); }, // tab 全部 接口调用 tabAllData:function(ky,st,or,crt,cn){ $.ajax({ url: 'http://enterprise.qbao.com/merchant/shop/qry/searchProducts.html?shopUserId=1779040&keyWord='+ ky +'&sortBy='+ st +'&orderBy='+ or +'¤tPage='+ crt, type: "POST", contentType: "application/x-www-form-urlencoded; charset=utf-8", success: function(data, status, jqXHR) { if(data && data.success == true) { $('.'+ cn +'').find(".initloading").addClass("hide"); main.totalCount = data.data.totalCount; main.allProductsCtn(data.data,cn); } else { $('.'+ cn +'').find(".initloading").addClass("hide"); main.prompt("请求错误!"); } }, error: function(){ $('.'+ cn +'').find(".initloading").addClass("hide"); main.prompt("请求错误!"); } }); }, // 商品的加载 allProductsCtn:function(_data,cn){ var products = _data.products, liHtml = ''; for(var p=0; p < products.length; p++){ liHtml += '<li data-id='+ products[p].id +'>'+ '<a href="'+ products[p].spuName+'">'+ ' <img src="'+ products[p].mainImg+'"/>'+ ' <div class="infoText borderTop">'+ ' <p class="text_overflow name clearfix">'+ products[p].spuName; liHtml += (main.rzfalse == 1 ? '<em class="quan"></em>':''); liHtml +='</p>'+ ' <p class="clearfix pric">'+ ' <span class="left">'+ ' <em class="bao backionic"></em>'+ ' <span class="font_14">'+ products[p].viewPrice +'</span>'+ ' </span>'+ ' <span class="right grey">已售'+ products[p].salesNumAggregated +'</span>'+ ' </p>'; liHtml += (main.fsfalse == 1?'<p class="grey"><em class="penalty backionic"></em>假一罚十</p>':''); liHtml += ' </div>'+' </a>'+ '</li>'; } if(cn == "pric"){ $("#thelist").find('.'+ cn +'').find("ul").children().remove(); $("#thelist").find('.'+ cn +'').find("ul").append(liHtml); main.nextPageNumb ++ ; //_shop.flag = true; }else{ $("#thelist").find('.'+ cn +'').find("ul").append(liHtml); main.nextPageNumb ++ ; //_shop.flag = true; } }, // 加载下一页内容 nexPageCtn:function(){ alert("eee"); }, // 错误提示框 prompt:function(text){ $("body").append('<div class="promptCover">'+ text +'</div>'); var width = $(".promptCover").width(); $(".promptCover").css("margin-left",-(width/2)+"px").fadeIn("slow"); setTimeout(function(){ $(".promptCover").fadeOut("slow").remove(); },10000); }, // 初始化加载 方法 init:function(){ main._search(); main.tab(); main.tabAllData(main.keyWord,2,1,1,"ch"); }, } main.init(); });
店铺装修JS
ajax URL的集中定义, 然后用banner.url.xx 访问,这样整个界面访问到了哪些url都是一目了然的
banner.url = { head: "http://enterprise.qbao.com", //head: "http://192.168.103.150:6070", getList: "/company/merchant/banner/list.html?_merchant_user_id_="+merchant_user_id, add: "/company/merchant/banner/add.html?_merchant_user_id_="+merchant_user_id, update: "/company/merchant/banner/update.html?_merchant_user_id_="+merchant_user_id, check: "/company/merchant/banner/approval/check.html?_merchant_user_id_="+merchant_user_id, uploadImg: "/qiniu/image/upload.html?_merchant_user_id_="+merchant_user_id, logo: "/company/merchant/shop/logo/update.html?_merchant_user_id_="+merchant_user_id, //标识 cover: "/company/merchant/shop/cover/update.html?_merchant_user_id_="+merchant_user_id, //封面 del: "/company/merchant/banner/remove.html?_merchant_user_id_="+merchant_user_id };
total
function tip(message) { var tip = "<div id='error_tip' class='error-tip'></div>"; if (!$("#error_tip")[0]) { $("body").append(tip); } var h = $("#error_tip").width(); $("#error_tip").css("margin-left", -h / 2).html(message).show(); setTimeout(function() { $("#error_tip").hide().html(""); }, 3000); }; (function() { jQuery.urlParam = function(name){var result = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1];return decodeURIComponent(result);} var merchant_user_id = $.urlParam('_merchant_user_id_'); //var merchant_user_id = '3896188'; var typeModule=$('.tabs').find('.active').attr('type')=="web"?1:2; $(".bussiness-crumbs").replaceWith(QB.templates['operate-crumbs']({ managerName: "商家管理", name: "店铺装修" })); //simple replace String.prototype.template = function() { var args = arguments, k = -1; return this.replace(/\{(\w+)\}/g, function() { k++; return args[k]; }); }; String.prototype.trim = function() { return this.replace(/(^\s+)|(\s+$)/g, ""); } var userAgent = navigator.userAgent.toLowerCase(); var browser = { version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1], safari: /webkit/.test( userAgent ), opera: /opera/.test( userAgent ), msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ), mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ) }; function uploadLogo(o, file, progress, fn) { var iframe = false; if(browser.msie && browser.version < 10){ iframe = true; } o.fileupload({ url: banner.url.head + banner.url.uploadImg, dataType: 'json', iframe: iframe, formData: { name: file } }).on('fileuploadprogressall', function(e, data) { //todo progress.call(this, arguments); }).on('fileuploaddone', function(e, data) { //todo if ( data.result ) { if (data.result.data) { fn.call(this, data); } else { tip(data.result.message); $uploadObj.find(".upload-image-name").html("<img src='" + uploadImgUrl + "' />") } } else { tip("上传错误!"); } }).on('fileuploadfail', function(e, data) { tip("上传错误!"); }); }; function uploadImg(o, file) { var iframe = false; if(browser.msie && browser.version < 10){ iframe = true; } o.fileupload({ url: banner.url.head + banner.url.uploadImg, dataType: 'json', iframe: iframe, dataType: 'json', formData: { name: file } }).on('fileuploadprogressall', function(e, data) { //todo var p = $(this).parents("tr"); if ( p.find(".upload-image-name img").length == 0 ) { } else { uploadImgUrl = p.find(".upload-image-name").find("img")[0].src; } p.find(".upload-wrap").css("background", "url(/images/rzwait.gif) center center no-repeat") p.find(".upload-image-name").html("").attr("key", 0); }).on('fileuploaddone', function(e, data) { if ( data.result ) { if (!data.result.data) { var p = $(this).parents("tr"); p.find(".upload-image-name").html("<img src='" + uploadImgUrl + "' />").attr("key", 1); tip(data.result.message); } else { var p = $(this).parents("tr"), d = data.result, key = Number(p.find(".join-product").attr("key")), havaRecode = p.attr("have"), btn = ""; if (p.find(".empty-upload")) { p.find(".empty-upload").remove(); } p.find(".upload-wrap").css("background-image", "none"); p.find(".upload-image-name").html("<img src='" + d.data.imageUrl + "' />").attr("key", 1); p.find(".upload-wrap").addClass("have-banner"); if (havaRecode == "ok") { btn = banner.option.btn.template("use-btn save-btn", "", "保存"); } else { if (key) { btn = banner.option.btn.template("use-btn save-btn", "", "保存"); } else { btn = banner.option.btn.template("save-btn", "disabled", "保存"); } } p.find("td:eq(4)").html(btn); } } else { tip("上传错误!"); } }).on('fileuploadfail', function(e, data) { tip("上传错误!"); }); }; var dialog = {}, banner = {}; var uploadImgUrl = "", $uploadObj = $("#shopCover"); dialog.setPosition = function(obj) { if (!obj) return false; var height = obj.height(); obj.css("margin-top", -height / 2); } dialog.open = function(obj) { dialog.setPosition(obj); obj.show(); $(".shadow:eq(0)").show(); } dialog.close = function(obj) { obj.hide(); $(".shadow:eq(0)").hide(); } banner.url = { head: "http://enterprise.qbao.com", //head: "http://192.168.103.150:6070", getList: "/company/merchant/banner/list.html?_merchant_user_id_="+merchant_user_id, add: "/company/merchant/banner/add.html?_merchant_user_id_="+merchant_user_id, update: "/company/merchant/banner/update.html?_merchant_user_id_="+merchant_user_id, check: "/company/merchant/banner/approval/check.html?_merchant_user_id_="+merchant_user_id, uploadImg: "/qiniu/image/upload.html?_merchant_user_id_="+merchant_user_id, logo: "/company/merchant/shop/logo/update.html?_merchant_user_id_="+merchant_user_id, //标识 cover: "/company/merchant/shop/cover/update.html?_merchant_user_id_="+merchant_user_id, //封面 del: "/company/merchant/banner/remove.html?_merchant_user_id_="+merchant_user_id }; banner.option = { btn: '<input class="tool-btn {optionbtn}" {disabled} type="button" name="" value="{toolbtn}" />', getList: function() { $("#bannerList tbody").children().remove(); var temp = $("#addBanner").val(), empty = $("#nullBanner").val(), status = banner.option.ckType; $.ajax({ type: "POST", url: banner.url.head + banner.url.getList, dataType: "json", data:{display:typeModule}, success: function(data) { if (data.success) { var c = data.data, d = c.list, len = d.length, tem = "", j = 0; for (var i = 0; i < 5; i++) { if (i < len) { var joinBtn = "", joinproduct = '<h3>' + d[i].goodsName + '</h3><p pid="' + d[i].goodsId + '">ID:' + d[i].goodsId + '</p>'; if (d[i].checkStatus != 1) { joinBtn = banner.option.btn.template("use-btn join-btn", "", "替换") tem = temp.template(i + 1, d[i].id, "have-banner", d[i].imgPath, i, d[i].goodsImg, joinBtn, joinproduct, status(d[i].checkStatus)["desc"].template(d[i].checkTime), status(d[i].checkStatus)["btn"]); } else { joinBtn = banner.option.btn.template("join-btn", "disabled", "替换") tem = temp.template(i + 1, d[i].id, "", d[i].imgPath, i, d[i].goodsImg, joinBtn, joinproduct, status(d[i].checkStatus)["desc"].template(d[i].checkTime), status(d[i].checkStatus)["btn"]); } $("#bannerList tbody").append(tem); } else { $("#bannerList tbody").append(empty.template(i + 1, i, i)); uploadImg($("#bannerList .empty-upload").eq(j), "file" + i); j++; } uploadImg($("#bannerList .reupload").eq(i), "reupload" + i); } if (c.logoPath) { $("#shopLogo>div").css("background-image", "none").addClass("have-banner"); $("#shopLogo .upload-image-name").html('<img src="' + c.logoPath + '" />'); } if (c.cover) { $("#shopCover>div").css("background-image", "none").addClass("have-banner"); $("#shopCover .upload-image-name").html('<img src="' + c.cover + '" />'); } $(".deleteBtn").on("click", function() { var _this = $(this); var bannerId = parseFloat( _this.parents("tr").find("td").eq(1).text() ); var url = banner.url.head + banner.url.del; $.ajax({ type: "POST", url: url, dataType: "json", data:{display:typeModule, bannerId:bannerId }, success: function(data) { if (data.success) { banner.option.getList(); } else { tip(data.message); } }, error: function(message) { tip(message); } }); }); } }, error: function(message) { tip(message); } }); }, add: function(url, goodsID, p) { $.ajax({ type: "POST", url: banner.url.head + banner.url.add, dataType: "json", data: { imgPath: url, goodsId: goodsID, display:typeModule }, success: function(data) { if (data.success) { banner.option.getList(); } else { tip(data.message); } }, error: function(message) { tip(message); } }); }, update: function(id, url, goodsID, p) { $.ajax({ type: "POST", url: banner.url.head + banner.url.update, dataType: "json", data: { id: id, imgPath: url, goodsId: goodsID, display:typeModule }, success: function(data) { if (data.success) { banner.option.getList(); } else { tip(data.message); } }, error: function(message) { tip(message); } }); }, check: function(id, fn) { $.ajax({ type: "POST", url: banner.url.head + banner.url.check, dataType: "json", data: { id: id, display:typeModule }, success: function(data) { if (data.success) { fn.call(this, data); } }, error: function(message) { tip(message); } }); }, ckType: function(status) { if (status.toString().length == 0) return false; var desc = '', btn = banner.option.btn, reason = "<p>很抱歉,您上传的banner不符合规范,无法通过审核,请您重新上传。<i></i></p>"; switch (status) { case 0: desc = ""; btn = btn.template("use-btn check-btn", "", "提交审核"); break; case 1: desc = '<div class="upload-check">审核中</div>'; btn = btn.template("check-btn", "disabled", "提交审核"); break; case 2: desc = '<div class="upload-check">审核通过</div><div class="check-time">{time}</div>'; btn = btn.template("check-btn", "disabled", "提交审核"); break; case 3: desc = '<div class="upload-check">审核未通过' + reason + '</div><div class="check-time">{time}</div>'; btn = btn.template("check-btn", "disabled", "提交审核"); break; default: desc = ""; btn = btn.template("use-btn check-btn", "", "提交审核"); break; } return { desc: desc, btn: btn }; }, updateImg: function(url, option) { option['display']=typeModule; $.ajax({ type: "POST", url: banner.url.head + url, dataType: "json", data: option, success: function(data) { if (data.success) {} }, error: function(message) { tip(message); } }); } }; //初始化 banner.option.getList(); //商家标识 uploadLogo($("#bz"), "newbz", function() { if ($("#shopLogo .upload-image-name img").length == 0) { } else { uploadImgUrl = $("#shopLogo .upload-image-name img")[0].src; } $uploadObj = $("#shopLogo"); $("#shopLogo .upload-image-name").html(""); $("#shopLogo>div").css("background-image", "url(/images/rzwait.gif)"); }, function(data) { var imgUrl = data.result.data.imageUrl; $(this).remove(); $("#shopLogo>div").css("background-image", "none").addClass("have-banner"); $("#shopLogo .upload-image-name").html('<img src="' + imgUrl + '" />'); banner.option.updateImg(banner.url.logo, { logoPath: imgUrl }); }); uploadLogo($("#rebz"), "bz", function() { if ($("#shopLogo .upload-image-name img").length == 0) { } else { uploadImgUrl = $("#shopLogo .upload-image-name img")[0].src; } $uploadObj = $("#shopLogo"); $("#shopLogo .upload-image-name").html(""); $("#shopLogo>div").css("background-image", "url(/images/rzwait.gif)"); }, function(data) { var imgUrl = data.result.data.imageUrl; $("#shopLogo>div").css("background-image", "none").addClass("have-banner"); $("#shopLogo .upload-image-name").html('<img src="' + imgUrl + '" />'); banner.option.updateImg(banner.url.logo, { logoPath: imgUrl }); }); //商家封面 uploadLogo($("#cov"), "newcov", function() { // $("#shopCover .upload-image-name").html(""); if ($("#shopCover .upload-image-name img").length == 0) { } else { uploadImgUrl = $("#shopCover .upload-image-name img")[0].src; } $uploadObj = $("#shopCover"); $("#shopCover .upload-image-name").html(""); $("#shopCover>div").css("background-image", "url(/images/rzwait.gif)"); }, function(data) { var imgUrl = data.result.data.imageUrl; $(this).remove(); $("#shopCover>div").css("background-image", "none").addClass("have-banner"); $("#shopCover .upload-image-name").html('<img src="' + imgUrl + '" />'); banner.option.updateImg(banner.url.cover, { cover: imgUrl }); }); uploadLogo($("#recov"), "cov", function() { //$("#shopCover .upload-image-name").html(""); if ($("#shopCover .upload-image-name img").length == 0) { } else { uploadImgUrl = $("#shopCover .upload-image-name img")[0].src; } $uploadObj = $("#shopCover"); $("#shopCover .upload-image-name").html(""); $("#shopCover>div").css("background-image", "url(/images/rzwait.gif)"); }, function(data) { var imgUrl = data.result.data.imageUrl; $("#shopCover>div").css("background-image", "none").addClass("have-banner"); $("#shopCover .upload-image-name").html('<img src="' + imgUrl + '" />'); banner.option.updateImg(banner.url.cover, { cover: imgUrl }); }); $("#bannerList").delegate('.save-btn', 'click', function() { var p = $(this).parents("tr"), goodsID = p.find(".join-info>p").attr("pid"), imgUrl = p.find(".upload-image-name>img").attr('src'), havaRecode = p.attr("have"); if (havaRecode == "ok") { banner.option.update(p.find("td:eq(1)").html(), imgUrl, goodsID, p); } else { banner.option.add(imgUrl, goodsID, p); } }); $("#bannerList").delegate('.check-btn', 'click', function() { var p = $(this).parents("tr"), id = p.find("td:eq(1)").html(), ck = banner.option.ckType(1); banner.option.check(id, function(data) { banner.option.getList(); }); }); //关联商品 $("#bannerList").delegate('.join-btn', 'click', function() { var dialogBox = $(".dialog").eq(0); dialog.setPosition(dialogBox); dialog.open(dialogBox); $("#mainContent input[type='radio']").attr("checked", false); $("#bannerSelect").attr("bannerID", $(this).parents("tr").index()); }); $(".dialog-close,.cancle-btn").bind("click", function() { var dialogBox = $(".dialog").eq(0); dialog.close(dialogBox); }); $("#mainContent").delegate("input[type='radio']", 'change', function() { var index = $(this).parents("tr").index(), value = []; value.push($(this).parents("tr").find(".image-box>img").attr("src")); value.push($(this).parents("tr").find(".product-detail>h4").html()); value.push($(this).parents("tr").find(".product-id>span").html()); $("#bannerSelect").val(value.join(",")); }); $("#confirmBtn").bind('click', function() { var v = $("#bannerSelect").val().trim().split(","), dialogBox = $(".dialog").eq(0), index = $("#bannerSelect").attr("bannerID"); if ($("#bannerSelect").val().trim().length != 0) { var o = $("#bannerList tbody tr").eq(index), key = Number(o.find(".upload-image-name").attr("key")), havaRecode = o.attr("have"), btn = ""; o.find(".join-image>div").html("<div class='imgbox'><img src='" + v[0] + "' /></div>"); o.find(".join-btn").val("替换"); o.find(".join-info>h3").html(v[1]); o.find(".join-info>p").html("ID:" + v[2]).attr("pid", v[2]); $("#bannerSelect").val("").attr("bannerID", ""); o.find(".join-product").attr("key", 1); if (havaRecode == "ok") { btn = banner.option.btn.template("use-btn save-btn", "", "保存"); } else { if (key) { btn = banner.option.btn.template("use-btn save-btn", "", "保存"); } else { btn = banner.option.btn.template("save-btn", "disabled", "保存"); } } o.find("td:eq(4)").html(btn); dialog.close(dialogBox); } else { tip("请选择商品!"); } }); function timeFormat(time) { var d = new Date(time), day = [d.getFullYear(), d.getMonth() + 1, d.getDate()], times = [d.getHours(), d.getMinutes(), d.getSeconds()] return day.join("-") + " " + times.join(":"); } function timeFormatStr(time) { return time.split(" ")[0] + " " + time.split(" ")[1]; } function getKey(pageID) { var key = $("#mainContent .select-search:eq(0)").attr("key"), value = $("#productCondition").val().trim(); if (key == "name") { var reg1 = /^[A-Za-z0-9\u4e00-\u9fa5]+$/; if (!reg1.test(value) && value.length != 0) { tip("请输入合法的商品名称!"); return false; } page.getList(pageID, value); } else { var reg2 = /^[0-9]+$/; if (!reg2.test(value) && value.length != 0) { tip("请输入正确的商品ID!"); return false; } page.getList(pageID, "", value); } } function setM(money) { var reg = /(\d{1,3})(?=(\d{3})+(?:$|\.))/g; return money.toString().replace(reg, "$1,"); } var page = {}; page.url = { getproduct:"http://enterprise.qbao.com/merchant/shop/qry/searchProducts.html" //getproduct: "http://goods.qbao.com/goodsProduct/getSpuFromSolr.html?_merchant_user_id_="+merchant_user_id //获取商品list }; page.len = 5; page.pageNum = 1; page.current = function() { return $("#page").attr("currentpage"); } page.next = function() { //next var currentPage = parseInt(page.current()), totalPage = parseInt(page.totalPage()); if (totalPage > currentPage) { currentPage = currentPage + 1; //page.getList(currentPage, option.name, option.id); getKey(currentPage); } else { return false; } } page.prev = function() { //prev var currentPage = parseInt(page.current()); if (currentPage > 1) { currentPage = currentPage - 1; //page.getList(currentPage, option.name, option.id); getKey(currentPage); } else { return false; } } page.random = function(pageID) { //random page getKey(pageID); } page.totalPage = function() { return page.pageNum; } page.centerPages = function(pageID) { var centerPages = []; centerPages.push("<em>" + (pageID - 1) + "</em>"); centerPages.push("<span>" + pageID + "</span>"); centerPages.push("<em>" + (pageID + 1) + "</em>"); return centerPages.join(""); } page.outPages = function(pageID, setLen) { var outPages = []; if (setLen == undefined) { setLen = 4; } for (var i = 1; i <= setLen; i++) { if (pageID == i) { outPages.push("<span>" + i + "</span>"); } else { outPages.push("<em>" + i + "</em>"); } } return outPages.join(""); } page.rightPages = function(pageID, total) { var rightPages = []; for (var i = total - 3; i <= total; i++) { if (pageID == i) { rightPages.push("<span>" + i + "</span>"); } else { rightPages.push("<em>" + i + "</em>"); } } return rightPages.join(""); } page.init = function(pageID) { var perpage = [], totalPage = page.totalPage(); perpage.push("<b>prev</b>"); if (totalPage < 6) { perpage.push(page.outPages(pageID, totalPage)); } else { if (pageID <= 3) { perpage.push(page.outPages(pageID)); perpage.push("<i>...</i>"); perpage.push("<em>" + totalPage + "</em>"); } else if (pageID >= totalPage - 2) { perpage.push("<em>1</em>"); perpage.push("<i>...</i>"); perpage.push(page.rightPages(pageID, totalPage)); } else { perpage.push("<em>1</em>"); perpage.push("<i>...</i>"); perpage.push(page.centerPages(pageID)); perpage.push("<i>...</i>"); perpage.push("<em>" + totalPage + "</em>"); } } perpage.push("<b>next</b>"); if (totalPage <= 1) { $("#page").hide() } else { $("#page").show().html(perpage.join("")); } } page.getList = function(pageID, supName, supId) { //@pageID var tem_position = $('#mainContent tbody'); if (pageID == undefined) { tem_position.empty().append('<tr><td colspan="6" style="padding:20px 0;">没有关联商品</td></tr>'); return false; } $.ajax({ type: "POST", url: page.url.getproduct, data: { "shopUserId": '1779040', "currentPage":page.pageNum, "pageSize":page.len, "sortBy":0, "orderBy":0, "keyWord":supName }, success: function(data) { if (data.success) { var total = 0; if(data.data.totalCount % page.len===0){ total =data.data.totalCount/page.len; }else{ total =parseInt(data.data.totalCount/page.len)+1; } var list = data.data.products, pTemp = $("#productTemp").val(), pList = []; if (total) { for (var i = 0; i < list.length; i++) { var p = list[i]; //timeFormatStr() pList.push(pTemp.template(p.mainImg, p.spuName, p.id, p.viewPrice == 0 ? "面议" : setM(p.viewPrice))); } } else { tem_position.empty().append('<tr><td colspan="6" style="padding:20px 0;">没有关联商品</td></tr>'); $("#page").hide().html(""); return false; } page.pageNum = total; tem_position.empty().append(pList.join("")); $("#page").attr({ "currentpage": pageID }); page.init(pageID); } else { tip(data.message); } }, error: function(data) { tip("请求失败"); } }); } page.getList(1); $("#page").delegate("em", "click", function() { var pageID = parseInt($(this).html()); page.random(pageID); page.init(pageID); $("#page").attr("currentpage", pageID) }); $("#page").delegate("b:first", "click", function() { var pageID = parseInt($("#page").attr("currentpage")); page.prev(pageID); }); $("#page").delegate("b:last", "click", function() { var pageID = parseInt($("#page").attr("currentpage")); page.next(pageID); }); $("#mainContent .dialog-search").find("span").hover(function() { $(">dl", $(this)).show(); }, function() { $(">dl", $(this)).hide(); }); $("#mainContent dd").bind('click', function() { $(".select-search").eq(0).html($(this).html()).attr("key", $(this).attr("value")); $(this).parent().hide(); }); $("#searchBtn").bind('click', function() { getKey(1); }); $('.tabs').delegate('.menu','click',function(){ $('.tabs li').removeClass('active'); $(this).addClass('active'); typeModule=$(this).attr('type')=='web'?1:2; if(typeModule === 1){ $('#app-size').hide(); $('#pc-size').show(); }else{ $('#app-size').show(); $('#pc-size').hide(); } //初始化 banner.option.getList(); }); })(window); QB.SiteMenu.activeOn('#shop-finish');