学习笔记
思想:
1、通过添加特殊属性为优先级赋值
2、定义一个临时数组 对需要展示的数据进行排序并保存
3、移除未排序前展示的容器
4、添加新的容器
5、根据特殊属性 添加颜色
未按照优先级排序
排序后
1、通过添加特殊属性为优先级赋值
优先级 剧毒品>易燃易爆>腐蚀品>危险品
html代码
<div style="display: grid;
border:1px solid black;
border-bottom:none;
border-right:none;
width:80%;grid-template-columns:1fr 1fr 1fr 1fr 1fr 1fr " class='box'>
<?php if (!empty($laboratoryList)) { ?>
<?php foreach ($laboratoryList as $item) { ?>
<div class="sty2" dataType='<?= $item['data_type'] ?>' style=" border-bottom:1px solid black;border-right:1px solid black; text-align: center;font-size:18px"><?= $item['laboratory_name'] ?></div>
<?php }
} else { ?>
<?php } ?>
</div>
js代码
$('.sty2').each(function() {
if ($(this).attr('dataType') == '易燃易爆品') {
$(this).attr('priority', 3)
} else if ($(this).attr('dataType') == '剧毒品') {
$(this).attr('priority', 4)
} else if ($(this).attr('dataType') == '腐蚀品') {
$(this).attr('priority', 2)
} else if ($(this).attr('dataType') == '危险品') {
$(this).attr('priority', 1)
}
})
2、定义一个临时数组 对需要展示的数据进行保存
js代码
var arr = [] //临时数组
$('.box>div').each(function() {
var obj = {} //对象保存需要展示的属性
obj.priority = $(this).attr('priority')
obj.content = $(this).text()
arr.push(obj)
})
//冒泡排序 根据优先级排序
for (var i = 0; i < arr.length - 1; i++) {
for (j = 0; j < arr.length - 1 - i; j++) {
if (arr[j].priority < arr[j + 1].priority) {
var max = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = max;
}
}
}
3、移除未排序前展示的容器
$('.sty2').remove()
4、添加新的容器
for (var i = 0; i < arr.length; i++) {
$('.box').append('<div class="box1" priority="' + arr[i].priority + '" style="border-bottom:1px solid black;border-right:1px solid black;display:flex;align-items: center; justify-content: center;font-size:18px;height:40px" >' + arr[i].content + '<div>')
}
5、根据特殊属性 添加颜色
$('.box1').each(function() {
if ($(this).attr('priority') == 3) {
$(this).css('background', 'rgb(255,255,102)')
} else if ($(this).attr('priority') == 4) {
$(this).css('background', 'rgb(255,204,204)')
} else if ($(this).attr('priority') == 2) {
$(this).css('background', 'rgb(255,255,204)')
} else if ($(this).attr('priority') == 1) {
$(this).css('background', 'rgb(255,204,102)')
}
})