Javascript设置特殊属性
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javascript设置特殊属性相关的知识,希望对你有一定的参考价值。
1、设置和获取特殊属性
setAttribute("score",10);设定一些DOM元素属性名特殊的属性
getAttribute("score");获取设置属性的值
2、示例
示例:五角星评分系统
静态分数
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>javascript测试</title> <style type="text/css"> table{ width:300px; height:30px; text-align: center; border-collapse: collapse; cursor: pointer; } table td{ border:solid 1px blue; } </style> <script type="text/javascript"> onload = function(){ var tdObjs = document.getElementById(‘tb‘).getElementsByTagName("td"); for(var i=0;i<tdObjs.length;i++) { tdObjs[i].onmouseover = function(){ var score = parseInt(this.getAttribute("score"));//转换为整数 for(var j=0;j<tdObjs.length;j++) { if(parseInt(tdObjs[j].getAttribute("score"))<=score)//如果不转换为整数,数量超过10个时,这里就会出问题 { tdObjs[j].textContent = "★"; tdObjs[j].style.color = "red"; } } }; tdObjs[i].onmouseout = function(){ for(var j=0;j<tdObjs.length;j++) { tdObjs[j].textContent = "☆"; tdObjs[j].style.color = ""; } }; tdObjs[i].onclick=function(){ var score = this.getAttribute("score"); alert("当前分数为:"+score+"分"); }; } }; </script> </head> <body> <table id="tb"> <tr> <td score="10">☆</td> <td score="20">☆</td> <td score="30">☆</td> <td score="40">☆</td> <td score="50">☆</td> </tr> </table> </body> </html>
效果图
动态分数
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>Javascript测试</title> <style type="text/css"> table{ width:300px; height:30px; text-align: center; border-collapse: collapse; cursor: pointer; } table td{ border:solid 1px blue; } </style> <script type="text/javascript"> onload = function(){ var tdObjs = document.getElementById(‘tb‘).getElementsByTagName("td"); for(var i=0;i<tdObjs.length;i++) { tdObjs[i].setAttribute("score",(i+1)*10); } for(var i=0;i<tdObjs.length;i++) { tdObjs[i].onmouseover = function(){ var score = parseInt(this.getAttribute("score"));//转换为整数 for(var j=0;j<tdObjs.length;j++) { if(parseInt(tdObjs[j].getAttribute("score"))<=score)//如果不转换为整数,数量超过10个时,这里就会出问题 { tdObjs[j].textContent = "★"; tdObjs[j].style.color = "red"; } } }; tdObjs[i].onmouseout = function(){ for(var j=0;j<tdObjs.length;j++) { tdObjs[j].textContent = "☆"; tdObjs[j].style.color = ""; } }; tdObjs[i].onclick=function(){ var score = this.getAttribute("score"); alert("当前分数为:"+score+"分"); }; } }; </script> </head> <body> <table id="tb"> <tr> <td>☆</td> <td>☆</td> <td>☆</td> <td>☆</td> <td>☆</td> <td>☆</td> <td>☆</td> <td>☆</td> <td>☆</td> <td>☆</td> </tr> </table> </body> </html>
效果图
以上是关于Javascript设置特殊属性的主要内容,如果未能解决你的问题,请参考以下文章
javascript 用于在节点#nodejs #javascript内设置react app的代码片段
VSCode自定义代码片段12——JavaScript的Promise对象