【问题标题】:I am creating a social media sort of website, and I need to let the user dynamically post [closed]我正在创建一个社交媒体网站,我需要让用户动态发布 [关闭]
【发布时间】:2016-03-30 11:26:48
【问题描述】:

代码应该使用 js 动态添加一个新的文章元素。这是我的代码,但它不起作用。

一旦用户点击发布按钮,就会在页面上创建文章。 `

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 = document.getElementByID("posting-area").value;




    // test case, append the content
    document.body.appendChild(article);
    document.getElementById("myarticle").appendChild(p);

}

`

供用户输入帖子文本的html。

<article class="posts">
               <img 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>

【问题讨论】:

  • 除非您更具体,否则我们无法为您提供帮助。什么不工作? JavaScript 控制台中显示了哪些错误?

标签: javascript html dynamic posting


【解决方案1】:

我发现您的代码存在许多问题。首先,您将 p 元素附加到 id 为 myarticle 的元素,但 myarticle 在您的 html sn-p 中不存在。您可能已将其关闭。

另外,document.getElementByID("posting-area").value() 是错误的。应该是getElementById("posting-area").value()。去掉 getElementByID 中的大写 D。

最后,你需要换行

var p = document.createElement("p");
p = document.getElementById("posting-area").value;

var p = document.createElement("p");
p.innerHTML = document.getElementById("posting-area").value;

这是一个有效的jsfiddle

【讨论】:

  • 它正在工作,但是每当我点击帖子时,它都会将新的 div 添加到旧的 div 中。 @Robbert
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 2020-03-27
  • 2021-03-13
相关资源
最近更新 更多