請原諒我,因爲我只是一個OOPHP開發人員,但是,我正在嘗試將客戶端實時聊天與朋友*進行整合。如何爲每個()類創建點擊監聽器
我已經實際數據的演示版本,這裏是我當前的代碼:
var chat = {
\t open: function(id) {
\t console.log(id);
}
};
var chatBtns = document.getElementsByClassName('chat-single');
// WORKS
chatBtns[0].addEventListener('click', function() {
\t chat.open(this.getAttribute('id'));
});
/* DOESNT WORK
chatBtns.forEach(function(btn){
btn.addEventListener('click', function() {
\t chat.open(this.getAttribute('id'));
});
});
*/
a {
text-decoration: none;
color: blue;
}
a:hover {
color: purple;
}
.chat-wrapper {
padding: 20px;
}
.chat-single {
background: #efefef;
padding: 5px;
border: 1px solid #000;
}
<div class='chat-wrapper'>
<p class='online-friends'>
Online Friends: (<span class='chat-online'>2</span>)
</p>
<div class='chat-friends'>
<a class='chat-single' title='chat with Some Name' href='#' id='unique-id-here'>Some Name</a>
<a class='chat-single' title='chat with Some Other Name' href='#' id='unique-id-here'>Some Other Name</a>
</div>
</div>
爲好友*保持一個屬性id
內的唯一身份聊天。單擊每個按鈕(chat-single
)時將獲取id
屬性並將其發送到chat.open()
方法。
我已調試此代碼,並看到chatBtns
是一個數據類型的數組,因此,我看着forEach()
documentation。這裏的問題是,當我陳述0
索引點時,它的工作原理。當我使用forEach()
時,它給了我一個該方法不存在的錯誤。
這裏的任何幫助都是完美的,我是否也可以解釋它是如何工作的,以便我能理解我錯過了什麼。
請注意我不想使用任何庫來實現這個(即:jQuery)。
你可以使用一個簡單的for循環,或者通過像'Array.prototype.slice.call轉換成數組(document.getElementsByClassName(「聊天單」)) .forEach' –
這工作,我不明白爲什麼?我'console.log(chatBtns);'它已經是一個數組..你可以添加一個答案解釋?非常感謝@ E.Sundin – KDOT