js—新的选择器、获取class列表属性、 JSON新方法

xiaoxiao2021-02-28  79

新的选择器

<script> //新的选择器 querySelector、querySelectorAll window.onload = function(){ //var oDiv = document.querySelector('[title=hello]'); var oDiv = document.querySelector('.box'); //querySelector不支持IE6、7 只能选择一组中的第一个元素 var aDiv = document.querySelectorAll('.box'); //querySelectorAll获取一组元素 for(var i=0; i<aDiv.length; i++){ aDiv[i].style.background = "red"; } }; </script> <body> <div id="div1" class="box" title="hello">div</div> <div class="box">div2</div> </body>

获取class列表属性

<script> window.onload = function(){ var oDiv = document.getElementById('div1'); //alert( oDiv.classList ); //类似与数组的对象 //alert( oDiv.classList.length ); //3 oDiv.classList.add('box4'); //添加class oDiv.classList.remove('box2'); //删除class oDiv.classList.toggle('box2'); //切换class }; </script> </head> <body> <div id="div1" class="box1 box2 box3">div</div> </body>

JOSN新方法

<script> //eval : 可以解析任何字符串变成JS //parse : 只能解析JSON形式的字符串变成JS (安全性要高一些) var str = 'function show(){alert(123)}'; eval(str); show(); var str = '{"name":"hello"}'; //一定是严格的JSON形式 var json = JSON.parse(str); //解析JSON形式的字符串变成JS alert( json.name ); //hello var json = {name : "hello"}; var str = JSON.stringify(json); //解析JS变成JSON形式的字符串 alert( str ); //{"name" : "hello"} </script>
转载请注明原文地址: https://www.6miu.com/read-67762.html

最新回复(0)