DIV的事件监听器和更改内容

时间:2016-03-06 15:53:57

标签: javascript

我得到了这样的块:

<div class="listener" id="123">
<h1>Title</h1>Some text...
<div class="container"></div>
</div>

<br>

<div class="listener" id="456">
<h1>Title</h1>Some text...
<div class="container"></div>
</div>

CSS:

.listener{width:500px;background:red;border:1px solid black}

JavaScript的:

document.getElementByClassName("listener").addEventListener("click", function()

{

// get the id of the DIV
// put content inside the class=container inside the DIV with innerHTML

});

会发生什么?

点击其中一个框后:

  • 调用函数
  • 获取点击的DIV的ID
  • 将一些内容放入DIV(DIV with class = container)

请使用<a>或jQuery解决方案。

有什么想法吗?谢谢!

我有一个小提琴:https://jsfiddle.net/wwp9jk8t/

1 个答案:

答案 0 :(得分:1)

  

document.getElementByClassName("listener")将返回nodelist而不是DOM元素,并且无法click事件绑定到array-like NodeList以上。使用[].forEach.call / for-loop来迭代nodeList中的所有元素,并将adeventListener应用于每个元素。

note 拼写错误getElementByClassName,它应该是 getElementsByClassName (复数)

试试这个:

[].forEach.call(document.getElementsByClassName("listener"), function(elem) {
  elem.addEventListener("click", function() {
    alert(this.id);//to get the id attribute of the clicked element..    
    this.getElementsByClassName("container")[0].innerHTML = "Hello World";
  });
})
.listener {
  width: 500px;
  background: red;
  border: 1px solid black
}
<div class="listener" id="123">
  <h1>Title</h1>Some text...
  <div class="container"></div>
</div>

<br>

<div class="listener" id="456">
  <h1>Title</h1>Some text...
  <div class="container"></div>
</div>