2016-03-06 14 views
0

我有像這些塊:事件偵聽器DIV和變化內容

<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帶class =容器)

請與<a>或jQuery解決方案。

有什麼想法?謝謝!

我這裏有一個小提琴:https://jsfiddle.net/wwp9jk8t/

+0

見有這麼一個問題:HTTP:// stackoverflow.com/questions/3219758/detect-changes-in-the-dom – roland

+0

@roland - 您誤解了這個問題。它要求如何在收到點擊事件時更改DOM,而不是在更改DOM時觸發什麼事件。 – Quentin

+0

您有兩個問題:1.它是getElementsByClassName,而不是getElementByClassName,2.您無法將addEventListener調用到節點列表。您必須在節點列表中選擇一個節點,然後才能調用addEventListener。 –

回答

1

document.getElementByClassName("listener")將返回nodelist不是一個DOM元素,你不能綁定click事件超過array-like NodeList。使用[].forEach.call/for-loop迭代nodeList中的所有元素,並將adeventListener應用於每個元素。

而且錯字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>

+0

這太棒了!是否有可能獲得DIV的ID?因爲它應該通過Ajax加載內容('getdata.php?id = ....') – Chama

+0

檢查編輯.. – Rayon

+0

非常棒!我必須將JS代碼放在元素下面,對吧?如果使用ID重新加載新的div盒,腳本不起作用......任何想法如何刷新dom中元素的索引? – Chama