为什么hasClass函数在Javascript添加的类上返回false

时间:2015-12-07 10:06:07

标签: javascript

<script>
// function checks that element "elem" has class name "cname"

function hasClass(elem, cname) {
var classArr = elem.className.split(" ");
    for(c in classArr)
      {
          if(classArr[c] === "test")
              return true;
          else
              return false;
      }
}



// function adds class name "cname" to element "elem"
function addClass(elem, cname) {
   var classArr = elem.className.split(" ");
   classArr.push(cname);
   elem.className = classArr.join(" ");
 }

window.onload = function() {
// inside this function you can write some tests
    var box = document.getElementById('holder');
    addClass(box, 'test');
    addClass(box, 'testtest');
    console.log(box);
    console.log(hasClass(box, 'test'));     
};
</script>

/*<div id="holder">#holder<br>(block for tests)</div>

类是通过JS addClass函数添加的 我的问题是为什么console.log(hasClass(box,&#39; test&#39;))在添加类后会记录为false。* /

1 个答案:

答案 0 :(得分:0)

您还需要将此元素添加到正文中。将您的onload方法更改为

window.onload = function() {
// inside this function you can write some tests
    var box = document.getElementById('holder');
    document.body.appendChild(box );    
    addClass(box, 'test');
    addClass(box, 'testtest');
    console.log(box);
    console.log(hasClass(box, 'test'));     
};

同时更新了hasClassMethod

function hasClass(elem, cname) {
var classArr = elem.className.split(" ");
  console.log(classArr);
    for(c in classArr)
      {
        console.log(classArr[c]);
          if(classArr[c] === "test")
              return true;


      }
  return false;
}