JS 可以为任何HTML元素添加任意个 自定义属性
元素.属性名=属性值,如:aBtn.abc = 123;
例:
<input type="button" value="按钮1" /> <script> window.onload = function (){ var aBtn = document.getElementsByTagName('input')[0]; aBtn.abc = 123; // 添加自定义属性 abc aBtn.onclick = function(){ alert( aBtn.abc ); //弹出属性值为 123 } }; </script>
例:自定义属性应用——匹配数组内容
<!doctype html> <html> <head> <meta charset="utf-8"> <title>邦邦的小站_分享Web前端的学习心得!</title> <script> window.onload = function(){ var aBtn = document.getElementsByTagName('input'); var arr = ['Web前端','JavaScript','CSS3','邦邦的小站','jmsbang.com']; for(var i=0;i<aBtn.length;i++){ aBtn[i].num=0; aBtn[i].onclick = function(){ this.value=arr[this.num]; this.num++; if(this.num==arr.length){ this.num=0; } }; } }; </script> </head> <body> <input type="button" value="按钮"> <input type="button" value="按钮"> <input type="button" value="按钮"> </body> </html>
评论前必须登录!
注册