[英]How can I add an “img” tag to a “p” element in basic Javascript?
[英]How can I add an img element using javascript?
在我的網站上,用戶有一個文本區域,他/她可以在其中輸入帖子的文本或圖像,然后單擊a按鈕。 單擊的按鈕鏈接到Java腳本函數,該函數動態創建一個文章元素,其中包含帖子內容以及用戶名和個人資料圖片。 我擁有的代碼可以創建新的article元素,但是我面臨兩個問題:
這是我這部分的HTML
<article class="posts">
<img id = "profilePic" class="peopletofollowimg" src=Profile.jpg alt="View Profile Picture">
<textarea id="posting-area" rows="6" cols="90" placeholder="Share Your Thoughts!"></textarea>
<button onclick="createPost()" id="post-button">Post!</button>
</article>
<article id="myarticle" class="posts">
</article>
這是我的js代碼
<script>
document.getElementById("post-button").onclick = createPost;
var el = document.getElementById("post-button");
if (el.addEventListener)
el.addEventListener("click", createPost(), false);
else if (el.attachEvent)
el.attachEvent('onclick', createPost());
function createPost(){
var article = document.createElement("article");
article.setAttribute("id", "myarticle");
article.className = "posts";
var p = document.createElement("p");
//p.setAttribute("id", "postContent");
p.innerHTML = document.getElementById("posting-area").value;
var img = document.createElement("img");
//img.setAttribute=("src", document.getElementById("profilePic"));
// img.innerHTML = document.getElementById("profilePic");
img.getAttribute("src");
img.className = "peopletofollowimg";
// test case, append the content
document.body.appendChild(article);
document.getElementById("myarticle").appendChild(p);
document.getElementById("myarticle").appendChild(img);
}
</script>
ID必須是唯一的。 您正在創建具有與頁面上相同的ID的新元素,因此當您執行.getElementById("myarticle")
,它總是選擇找到的第一個.getElementById("myarticle")
。
無需創建和附加元素,然后選擇添加其內容,而只需立即添加內容。
function createPost(){
var article = document.createElement("article");
article.className = "posts";
var p = document.createElement("p");
p.innerHTML = document.getElementById("posting-area").value;
var img = document.createElement("img");
img.className = "peopletofollowimg";
article.appendChild(p);
article.appendChild(img);
document.body.appendChild(article);
}
不知道關於沒有固定src
的img
意味着什么,但是您可以輕松地為其提供所需的任何值。
img.src = "some/path/to/image.png";
就像Barmar關於綁定處理程序所說的那樣,您不應該調用該函數。 現在,您只綁定第一個。 如果您修復了調用,最終將其綁定兩次。
改為這樣做:
var el = document.getElementById("post-button");
if (el.addEventListener)
el.addEventListener("click", createPost, false);
else if (el.attachEvent)
el.attachEvent('onclick', createPost);
else
el.onclick = createPost;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.