js中封装类时候,为啥需要针对一个标签节点的多个类名进行split?不进行split时候筛选的结果也对的啊。
未采用split对一个类的对个标签进行分割。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div{
width: 20px;
height: 20px;
margin: 10px auto;
background-color: red;
}
</style>
<script type="text/javascript">
window.onload=function(){
function getClass(classname){
if (document.getElementsByClassName)
{
return document.getElementsByClassName(classname);
}
var arr=[];
var dom=document.getElementsByTagName("*");
for(var i=0;i<dom.length;i++)
{
if(dom[i].className==classname)
{
arr.push(dom[i]);
}
}
return arr;
}
console.log(getClass("demo"));
console.log(getClass("demo").length);
for(var i=0;i<getClass("demo").length;i++)
{
getClass("demo")[i].style.backgroundColor="yellow";
}
}
</script>
</head>
<body>
<div></div>
<div class="demo"></div>
<div></div>
<div class="test demo "></div>
<div></div>
<div></div>
<div class="demo"></div>
<div></div>
<div></div>
<div class="demo java"></div>
</body>
</html>
采用了split对一个标签的多个类名进行分割:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div{
width: 20px;
height: 20px;
margin: 10px auto;
background-color: red;
}
</style>
<script type="text/javascript">
window.onload=function(){
function getClass(classname){
if(document.getElementsByClassName)
{
return document.getElementsByClassName(classname);
}
var arr=[];
var doms=document.getElementsByTagName("*");
for(var i=0;i<doms.length;i++)
{
var txtarr=doms[i].className.split(" ");
for(var j=0;j<txtarr.length;j++)
{
if(txtarr[j]=classname)
{
arr.push(txtarr[j]);
}
}
}
return arr;
}
console.log(getClass("demo"));
console.log(getClass("demo").length);
for(var i=0;i<getClass("demo").length;i++)
{
getClass("demo")[i].style.backgroundColor="yellow";
}
}
</script>
</head>
<body>
<div></div>
<div class="demo"></div>
<div></div>
<div class="test demo "></div>
<div></div>
<div></div>
<div class="demo"></div>
<div></div>
<div></div>
<div class="demo java"></div>
</body>
</html>
结果都是一样的,为啥还需要对标签的类名进行分割呢?
上面两段代码都使用了
getElemnetsByClassName
方法,没有运行你写的 fallback 代码你可以学习一下如何在浏览器开发者工具中调试js代码