[英]Creating and showing div's with javascript
我正在嘗試創建一個朋友列表,為此,我將需要為每個朋友創建一個div。 我嘗試的代碼無效。
相關的JavaScript(位於頁面底部):
document.getElementById("name").innerHTML = user;
document.getElementById("profilePic").src = "users/" + user + "/profilePic.jpg";
var friends = ["Test"];
var friendArea = document.getElementById("friendsDiv");
for (i=0; i < friends.length; i++) {
var friendDiv = document.createElement("div");
friendDiv.setAttribute("class", "friend");
var friendImage = document.createElement("img");
friendImage.setAttribute("class", "friendImage");
friendImage.setAttribute("src", "users/" + friends[i] + "/profilePic.jpg");
friendDiv.appendChild(friendImage);
friendArea.appendChild(friendDiv);
}
相關CSS:
.friends {
width: 100%;
height: 90%;
overflow-x: hidden;
overflow-y: auto;
}
.tools {
width: 100%;
height: 10%;
box-shadow: 0px 0px 3px 1px #898989;
}
.friend {
width: 100%;
height: 20%;
padding: 1%;
}
.friendImage {
height: 80%;
width: auto;
border: medium #CCCCCC solid;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
}
HTML並不是很重要,但是我還是會包括它。
<div class="window">
<div class="rightCorner">
<img src="images/pPicTemp.png" id="profilePic">
</div>
<div class="holder" id="profileData">
<span id="name"></span>
</div>
<div class="sideBar">
<div class="friends" id="friendsDiv">
</div>
<div class="tools">
</div>
</div>
您沒有將friendImage
附加到friendDiv
。
它看起來應該像這樣:
var friends = ["Test"];
var friendArea = document.getElementById("friends");
for (i=0; i < friends.length; i++) {
var friendDiv = document.createElement("div");
friendDiv.setAttribute("class", "friend");
var friendImage = document.createElement("img");
friendImage.setAttribute("class", "friendImage");
friendImage.setAttribute("src", "users/" + friends[i] + "/profilePic.jpg");
friendDiv.appendChild(friendImage);
friendArea.appendChild(friendDiv);
}
另外,請確保將此腳本放在HTML <body></body>
標記的底部,以便HTML在JavaScript嘗試從頁面獲取元素之前已加載了整個文檔。
您的腳本是否在標簽中? 嘗試這樣做時是否還會加載文檔? 控制台說什么? 它沒有CSS工作嗎? 另外,如果照片路徑不起作用,則div中沒有其他內容,您是否嘗試輸出其他內容?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.