Javascript DOM问题。 (getElementsByClassName方法)

时间:2015-12-14 08:14:31

标签: javascript html css dom

我有3个div,第一个是id,第二个是同一个类。我为这3个div编写了一个带有javascript的EventListeners。我的第一个div的eventlistener与ID有关,但与getElementsByClassName()相关的第二个函数不起作用。这是我的代码



document.addEventListener("DOMContentLoaded", function() {
  var firstElement = document.getElementById('firstOne');
  firstOne.addEventListener('mouseout', function() {
    this.style.backgroundColor = 'red';
    this.style.border = '5px outset #00FF1E';
  });

  var secondElements = document.getElementsByClassName('secondOne');
  secondElements.addEventListener('click', function() {
    for (var i = 0; i < secondElements.length; i++) {
      secondElements[i].style.backgroundColor = 'red';
    }
  });
});
&#13;
#firstOne {
  height: 240px;
  width: 240px;
  border: 5px solid blue;
  background-color: orange;
  display: inline-block;
}
.secondOne {
  height: 240px;
  width: 240px;
  border: 5px solid green;
  background-color: skyblue;
  display: inline-block;
}
&#13;
<div id="firstOne"></div>
<div class="secondOne"></div>
<div class="secondOne"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

document.getElementsByClassName返回NodeList。由于您正在执行secondElements.addEventListener,因此会抛出错误 因为您无法将事件附加到NodeList。您始终将事件附加到Node

要解决此问题,请使用for循环(或NodeList组合,如果您对此感到满意)遍历.apply-forEach的元素,并单独附加事件侦听器。

document.getElementById始终返回Node(因为DOM中只有一个元素具有特定的id),因此firstOne.addEventListener有效。

代码示例:

var secondElements = document.getElementsByClassName('secondOne');

for(var i = 0, len = secondElements.length, elm; i < len; i++){
    elm = secondElements[i];

    elm.addEventListener('click', your_handler_function_here);
}

答案 1 :(得分:2)

getElementsByClassName()返回具有所有给定类名的所有子元素的类数组对象。

使用click循环播放,然后添加 var secondElements = document.getElementsByClassName('secondOne'); for (var i=0;i<secondElements.length; i++) { secondElements[i].addEventListener('click',function(){ for(var i = 0; i < secondElements.length ; i++){ secondElements[i].style.backgroundColor = 'red'; } }); } 事件;

    <?xml version="1.0" encoding="utf-8" ?>
 <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">
  NHibernate.Dialect.MySQLDialect
</property>

<property name="connection.provider">
    NHibernate.Connection.DriverConnectionProvider
</property>

<property name="connection.driver_class">
      NHibernate.Driver.MySqlDataDriver
</property>

<property name="connection.connection_string">
  Server=localhost;Database=db_opdsoft;User ID=root;Password=root
</property>

<mapping assembly="OPDSoft"></mapping>

</session-factory>

demo http://jsfiddle.net/yqec6aqs/