jQuery学习笔记

CSS+JQuery实现给一组元素动态的添加序号

2017-11-13  本文已影响280人  小人物的秘密花园

最近做项目,遇到需要实现对一组元素进行动态的排序并生成序号的功能,以下是具体实现:

1. 实现思路

给这组元素绑定点击事件,当点击某个元素时,判断是否已经排序,若已经排序则需要给这个已排序的元素重新进行排序,并且当前单击的元素要清除其序号,若是没有进行过排序,则获取已经排序了的元素,在得到的数组的长度上加1即是当前元素的序号;

2. 示例代码

html

<ul>

<li><span class="sort-item"></span>item1</li>

<li><span class="sort-item"></span>item2</li>

<li><span class="sort-item"></span>item3</li>

</ul>

css

html,body {

width: 100%;

height:  100%;

font-family: 'Microsoft YaHei';

}

ul, ul li {

list-style: none;

}

.order-list {

width:  60%;

margin: 30px auto;

}

.order-list  li {

width:  100%;

height:  34px;

line-height: 34px;

padding: 0 15px;

cursor:  pointer;

background: #f2f2f2;

margin:  10px 0;

border-radius: 5px;

}

.sort-item {

width:  15px;

height:  15px;

border:  1px solid #ccc;

float:  left;

background:  #ccc;

font-size:  12px;

margin-right:  10px;

margin-top: 10px;

text-align: center;

border-radius: 4px;

color:  #666;

}

.sort-item-select {

width: 15px !important;

height: 15px !important;

line-height: 15px;

border-radius: 100%;

border-color: #ff6600;

color: #ff6600;

background: none;

border-radius: 100%;

}

js

//给需要排序的选项绑定点击事件

$('.order-list li').bind('click',function() {

var that = this;

//检测是否已经排序?

if ($(that).attr('sorted') != 1) {//否

//获取已经排序了的元素,并且当前元素的序号应该在已排序元素长度的基础上加1

var checkLn = $(that).parent().find('li[sorted="1"]').length + 1;

//给当前元素设置排序的序号值以及颜色

$(that).find('span.sort-item').html(checkLn).addClass('sort-item-select');

//设置当前元素已经排序了

$(that).attr('sorted','1');

} else {//是,再次点击时需要清除需要,并重新排序

//获取当前元素的序号元素的内容

var checkLn = $(that).find('span.sort-item').html();

//遍历已排序元素,并判断当前元素和已排序的元素的大小

$(that).parent().find('li[sorted="1"]').each(function(index,ele) {

var nSpan = $(this).find('span.sort-item').html();

//大于零,则减一,重新给已排序的元素排序

if (nSpan - checkLn > 0) {

$(this).find('span.sort-item').html(nSpan - 1);

}

});

//移除序号以及样式

$(that).find('span.sort-item').html('').removeClass('sort-item-select');

$(that).attr("check", "");

}

});

上一篇 下一篇

猜你喜欢

热点阅读