当前位置:网站首页>对li类数组对象随机添加特性,并进行排序
对li类数组对象随机添加特性,并进行排序
2022-04-23 07:34:00 【beinlife】
<html>
<head>
<title>修改元素的属性</title>
<meta charset="utf-8" />
<script >
window.οnlοad=function(){
//获取ul下的所有li
var lis=document.querySelectorAll("ul li");
var nums=[];
//反复生成随机数:必须和lis的个数一样
while(nums.length < lis.length) {
var n=parseInt(Math.random()*lis.length+1);
if(nums.indexOf(n)==-1){
nums.push(n);
}
}
/*遍历生产的随机数,给每个li添加特性*/
for (var i = 0; i < nums.length; i++) {
lis[i].setAttribute("data-j",nums[i]);
}
/*
问题1:lis是类数组对象,没有sort方法
解决1:把类数组对象转化为标准数组对象
问题2:比较器*/
lis=Array.prototype.slice.call(lis);
lis=lis.sort(function(li1,li2){
var n1=parseInt(li1.getAttribute("data-j"));
var n2=parseInt(li2.getAttribute("data-j"));
return n1-n2;
});
for (var i = 0; i < nums.length; i++) {
console.log(lis[i].getAttribute("data-j")+lis[i].innerHTML);
}
}
</script>
</head><body>
<!--1. 使用自定义属性实现摇号排名-->
<ul>
<li>Eric</li>
<li>Scott</li>
<li>Jerry</li>
<li>Tom</li>
<li>Rose</li>
<li>John</li>
<li>Smith</li>
<li>Andy</li>
</ul>
</body>
</html>
版权声明
本文为[beinlife]所创,转载请带上原文链接,感谢
https://blog.csdn.net/beinlife/article/details/53012320
边栏推荐
- 为什么会存在1px问题?怎么解决?
- ATSS(CVPR2020)
- An example of network communication based on TCP / IP protocol -- file transmission
- My heart's broken! A woman's circle of friends envied others for paying wages on time and was fired. Even her colleagues who liked her were fired together
- form表单 post提交 数据量大的问题
- Flink SQL实现流批一体
- LeetCode简单题之统计字符串中的元音子字符串
- 作文以记之 ~ 二叉树的前序遍历
- 总线结构概述
- 青苹果影视系统源码 影视聚合 影视导航 影视点播网站源码
猜你喜欢
欧圣电气深交所上市:市值52亿 陆为东父女为美国籍
QT compilation qtxlsx Library
2022.4.11-4.17 AI industry weekly (issue 93): the dilemma of AI industry
A simple theme of Typecho with beautiful appearance_ Scarfskin source code download
利用Js实现一个千分位
There are some problems when using numeric type to query string type fields in MySQL
Green apple film and television system source code film and television aggregation film and television navigation film and television on demand website source code
输入/输出系统
Talk about the basic but not simple stock data
LeetCode简单题之三除数
随机推荐
LeetCode简单题之计算字符串的数字和
有意思的js 代码
[go] common concurrency model [generic version]
PyQt5开发之QTableWidget表头自定义与美化(附源代码下载)
项目上传部分
Discussion on ES6 tail tune optimization
One click cleanup of pycharm and jupyter cache files under the project
Somme numérique de la chaîne de calcul pour un problème simple de leetcode
怎么读书读论文
将实例化对象的方法 给新的对象用
英语课小记(四)
vmware 搭建ES8的常见错误
基于TCP/IP协议的网络通信实例——文件传输
LeetCode簡單題之計算字符串的數字和
Why are there 1px problems? How?
vslam PPT
Flink SQL实现流批一体
An idea plug-in that doesn't work, but can install X
网赚APP资源下载类网站源码
The third divisor of leetcode simple question