JavaScript未定义的疯狂

时间:2016-05-16 14:20:00

标签: javascript undefined typeof classname

var requestInfo;
var requestParent;

var switchButton = setInterval( function() {
  requestParent = document.getElementsByClassName("solid_color_2");
  if(typeof requestParent[0] != "undefined") {
   requestInfo = requestParent[0].getElementsByTagName('A');
   requestInfo[0].className = "";
   requestInfo[0].className = "instance-0";
   requestParent[0].className = "";
   requestParent[0].className = "button";
   requestInfo[0].style.backgroundColor = "#029c53";
   clearInterval(switchButton);
   console.log("interval last time");
  }
}, 1000);
  

无法执行" requestParent [0] .className =" button";

这里的标记:

<div class="button solid_color_2">
  <a class="primary-color instance-0" href="#">REQUEST INFO</a>
</div>

这里的错误: enter image description here

1 个答案:

答案 0 :(得分:3)

getElementsByClassName返回 live 节点列表,这意味着DOM中的更改会反映在列表中的更改中。

因此,使用此行,您将获得按钮元素的实时节点列表

requestParent = document.getElementsByClassName("solid_color_2");

然后用这条线......

requestParent[0].className = "";

您正在清除类名从列表中删除该元素,当您尝试更新时会导致错误。

您最好的选择是使用querySelectorAll来返回直播的HTML集合。您也可以删除设置className = ""的行。

var switchButton = setInterval( function() {

  // pay particular attention here because we're picking up
  // a element using it's *class*, hence .solid_color_2 and
  // not solid_color_2 (without the preceding dot)
  requestParent = document.querySelectorAll(".solid_color_2");
  if (typeof requestParent[0] != "undefined") {
   requestInfo = requestParent[0].querySelectorAll('a');
   requestInfo[0].className = "instance-0";
   requestParent[0].className = "button";
   requestInfo[0].style.backgroundColor = "#029c53";
   clearInterval(switchButton);
   console.log("interval last time");
  }
}, 1000);

DEMO