---
title: "jQuery01--推荐相册，就像一场海选"
author: "yumo12"
date: "2015-01-06T16:33:18Z"
tags: ["jQuery", "筛选"]
categories: ["Web前端"]
slug: "jquery01"
draft: false
lastmod: "2015-01-06T16:33:17Z"
id: 2173188
url: "https://yumo12.iteye.com/blog/2173188"
---

新年到了，我们的商户中心项目也在大家的努力下如期上线了。曾经一直觉得难度大的东西自己不会，简单的写出来又担心大家笑话，其实不过是给自己懒惰找的借口。就拿设置推荐相册来小结一下自己在这个项目中的收获吧。  
       如下图，左侧为商家的全部相册，右侧为推荐相册。在左边点击需要推荐的相册，相应位置显示红色边框作为标示，被选中的即可显示在右侧列表中，上限为8个。如果要取消推荐，点击右侧的删除按钮，同时左侧对应的红色边框也随之消失。最后，点击页面右下角的“提交”按钮即可设置完毕。  
[![album](http://blog.hapn.cc/wp-content/uploads/2015/01/album1.jpg)](http://blog.hapn.cc/wp-content/uploads/2015/01/album1.jpg)  
个人认为，推荐相册的设置，完全像是一场海选，此次设置8个名额。主人从全部相册中逐一抽取不重复的相册（最多8个），被抽到的相册会被标记出来，并派出“影子”带好自己的身份证件去右侧。这些影子可能会遭受主人的二次筛选，甚至有的会被打回原籍，对应的标记也会移除。最终胜利的才是象征店铺荣誉的推荐相册。

**首先需要我们布置好结构（此处样式省略）：**

左侧ul的id=”all”，右侧ul的id=”albumlist”。  
[![1211](http://blog.hapn.cc/wp-content/uploads/2015/01/1211.jpg)](http://blog.hapn.cc/wp-content/uploads/2015/01/1211.jpg)[![1222](http://blog.hapn.cc/wp-content/uploads/2015/01/1222.jpg)](http://blog.hapn.cc/wp-content/uploads/2015/01/1222.jpg)

**然后，我们来分析任务，理清思路：**

```
1. 点击左侧li时：
$("#all li").click(function(){
 （1）给被选中的li做个标记---checked。
    $(this).addClass('checked');
 （2）记住该li中图片的src，input的value，相册名称。让li的影子携带这些信息加入推荐相册的方队。
    var imgsrc = $(this).find('img').attr('src'),
        val = $(this).find('input').attr('value'), 
        pval = $(this).find('p').html(); 
    $('#albumList').append('<li>'+'<input type="hidden" name="'+type+'[]" value="'+val+'"><b class="del"></b><img src="'+imgsrc+'"/><p>'+pval+'</p></li>');
});
（3）好事多磨，最多只能有8个推荐。所以，我们还得设置一个max，并且根据max来判断。如果右边的li影子已经够8个，就要提示用户不能再添加了。
var max = <?=$max?>;
$("#all li").click(function(){
     var imgsrc = $(this).find('img').attr('src'),
         val = $(this).find('input').attr('value'), 
         pval = $(this).find('p').html(); 
     if($('#albumList').find('li').length<max&&!($(this).hasClass('checked'))){
         $(this).addClass('checked');
         $('#albumList').append('<li>'+'<input type="hidden" name="'+type+'[]" value="'+val+'"><b class="del"></b><img src="'+imgsrc+'"/><p>'+pval+'</p></li>');
     }else if($('#albumList').find('li').length>=max){
         alert("您已经推荐了"+max+"个了，不能再添加啦");
     }
});
```