我有四个div
元素,我的数组中有四个元素。我想得到这样的东西:
当用户点击第一个div
元素(class .news
)时,数组的第一个元素的“值”显示在div #selectedNews
内。
我的问题是我不明白如何关联div和数组元素。
再次编码:
var newsListData = [
{
"group" : "science",
"title" : "Text 1",
"image" : "images/news1.jpg",
"content" : "Text text text"
},
{
"group" : "science",
"title" : "Text 2",
"image" : "images/news2.jpg",
"content" : "Text text text"
},
{
"group" : "science",
"title" : 'Text 3',
"image" : "images/news3.jpg",
"content" : "Text text text"
},
{
"group" : "economics",
"title" : 'Text 4',
"image" : "images/news4.jpg",
"content" : "Text text text"
}]
var selected;
function elem() {
selected.innerHTML = "";
for (var i = 0; i < this.children.length; i++) {
selected.appendChild(this.children[i].cloneNode(true));
}
}
document.addEventListener("DOMContentLoaded", function() {
var selectedNews = newsListData /* stuck HERE */
for (var i = 0; i < selectedNews.length; i++) {
selectedNews[i].addEventListener("click", elem);
}
selected = document.getElementById("selectedNews")
});
#selectedNews {
border : 1px solid gray;
margin : 10px;
padding : 5px;
}
.news{
background-color : green;
border : 2px solid black;
padding : 4px;
margin-top : 2px;
text-align : center;
}
<div id="newsList">
<input type="text" placeholder="filter..." id="filter"/>
<div class="list">
<div id="0-news" class="news">One</div>
<div id="1-news" class="news">Two</div>
<div id="2-news" class="news">Three</div>
<div id="3-news" class="news">Last one</div>
<article id="selectedNews">
<h1>Titre</h1>
<figure>
<img src="" alt="titre"/>
</figure>
<div id="content">
bla bla
</div>
</article>
答案 0 :(得分:0)
您需要知道要显示的数组项的索引。我通过将事件监听器附加到.news
元素来实现,如下所示:
<div id="0-news" class="news" onclick="display(0)">One</div>
在你的JS中
window.display = function(index) {
var data = newsListData[index]; // get the right data from the array
...
}
DEMO https://jsfiddle.net/qqyvu3dm/4/
编辑循环创建数据按钮:
var newsList = document.getElementById("newsList");
var button;
for (var i = 0; i < newsListData.length; i++) {
// create button element in memory
button = document.createElement("button");
// set id attribute
button.setAttribute("id", index + "-news");
// attach event listener, pass i as pointer to your array element
button.onclick = display(i);
// append the button into #newsList div
newsList.appendChild(button);
}