使用JavaScript为提交按钮添加的帖子添加自动ID

时间:2018-07-18 09:51:04

标签: javascript html

我有一个表单,当用户多次单击“提交”按钮时,该表单允许用户发布添加的多个帖子。

我为使用HTML的帖子容器创建了一个模板,并使用JavaScript为它提供了自动id,但是当用户单击“提交”按钮时添加的帖子容器并没有自动id。如何使用JavaScript解决此问题?

下面是我的JS和HTML代码段

var myPost = document.querySelectorAll('.post-container'); //post container
var myDelBtn = document.querySelectorAll('.delete'); // delete icon

// loop for give id automatic
for (var i = 0; i < myPost.length; i++) {
  myPost[i].id = 'post-' + i;
  myDelBtn[i].id = 'post-' + i + '-delete';
};

function storeData() {
  var big = document.getElementById("contain"); // big container to append  new jumbotron child
  var postData = document.getElementById("comment").value; //value in text area
  var nDate = new Date().toLocaleString(); //convert date to day and hour format
  console.log(big);
  console.log(nDate);
  console.log(postData);

  // new jumborton template
  var newPost = '<div class="jumbotron post-container" id=" + myPost+">' +
    '<div class="media">' +
    '<a href="https://placeholder.com"><img  class="mr-3 rounded-circle" src="http://via.placeholder.com/64x64"></a>' +
    '<a class="font" href="#"><i class="fas fa-trash-alt delete" id="+ myDelBtn+"></i></a>' +
    '<div class="media-body">' +
    '<h4 class="mt-0 mb-0">Username</h4>' +
    '<span class="date text-muted">' + nDate + '</span>' +
    '<div class="text-justify mt-2">' + postData + '</div>' +
    '</div>' +
    '</div>' +
    '</div>';
  big.innerHTML += newPost;
}
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>java-task</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="../css/bootstrap.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
  <div class="container" id="wrapper">
    <div class="chatting-bot">
      <h1 class="text-center mb-4 mt-4"> Chatting System</h1>
      <form class="jumbotron pt-3" method="post">
        <div class="form-group row ">
          <label for="comment">Write Your Post</label>
          <textarea id="comment" name="comment" class="form-control" rows="3" placeholder="write your post"></textarea>
        </div>
        <button type="button" id="submit" class="btn btn-primary" onclick="storeData()">Post</button>
      </form>
    </div>
    <div class="posts" id="contain">
      <div class="jumbotron post-container" id="post-">
        <div class="media">
          <a href="https://placeholder.com"><img class="mr-3 rounded-circle" src="http://via.placeholder.com/64x64"></a>
          <a class="font" href="#"><i class="fas fa-trash-alt delete " id="post-0-delete"></i></a>
          <div class="media-body">
            <h4 class="mt-0 mb-0">Username</h4>
            <span class="date text-muted "> Posted on 7/14/2018, 11:10:05 am</span>
            <div class="text-justify mt-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
              book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
            </div>
          </div>
        </div>
      </div>
      <div class="jumbotron post-container" id="post-">
        <div class="media">
          <a href="https://placeholder.com"><img class="mr-3 rounded-circle" src="http://via.placeholder.com/64x64"></a>
          <a class="font" href="#"><i class="fas fa-trash-alt delete" id=""></i></a>
          <div class="media-body">
            <h4 class="mt-0 mb-0">Username</h4>
            <span class="date text-muted "> Posted on 7/14/2018, 11:10:05 am</span>
            <div class="text-justify mt-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
              book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script src="js/script.js" type="text/javascript"></script>
</body>

1 个答案:

答案 0 :(得分:1)

您的变量myPostmyDelBtn在页面的第一次加载时被初始化。并且您的循环仅在此之后被调用一次。因此,该循环影响2 .post-container的ID,然后不影响任何ID。

为了获得此迭代ID,您可以想象创建一个计数器,该计数器的开头是文章数,然后每次添加帖子时都添加+1。然后在HTML生成过程中直接输入此新的计数ID。

ps:如果您确实希望循环影响id,则可以在内部创建一个函数,声明新的数字.post-container,使用循环,然后在HTML生成后调用它。但是我认为这不是最好的方法,即您的用户每次创建新帖子时都会重新影响ID。

示例:

var myPost = document.querySelectorAll('.post-container'); //post container
var count = myPost.length;  // initialize counter
var myDelBtn=document.querySelectorAll('.delete'); // delete icon

// loop for give id automatic
 for (var i=0; i< myPost.length; i++){
   console.log(myPost.length);
     myPost[i].id = 'post-' + i;
     myDelBtn[i].id='post-'+i +'-delete';
 };




function storeData() {
    var big=document.getElementById("contain");   // big container to append  new jumbotron child
    var postData = document.getElementById("comment").value;  //value in text area
    var nDate = new Date().toLocaleString(); //convert date to day and hour format
    console.log(big);
    console.log(nDate);
    console.log(postData);
    count = count + 1;   // id counter
    console.log(count);
    // use counter directly inside HTML parsing
    var newPost = '<div class="jumbotron post-container" id="post-'+ count +'">'+
        '<div class="media">'+
        '<a href="https://placeholder.com"><img  class="mr-3 rounded-circle" src="http://via.placeholder.com/64x64"></a>'+
        '<a class="font" href="#"><i class="fas fa-trash-alt delete" id="post-'+ count + 'myDelBtn"></i></a>'+
        '<div class="media-body">'+
        '<h4 class="mt-0 mb-0">Username</h4>'+
        '<span class="date text-muted">'+ nDate +'</span>'+
        '<div class="text-justify mt-2">'+ postData +'</div>'+
        '</div>'+
        '</div>'+
        '</div>';
    big.innerHTML += newPost;
}
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>java-task</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="../css/bootstrap.css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="css/style.css">
    </head>
    <body>
        <div class="container" id ="wrapper">
            <div class="chatting-bot">
                <h1 class="text-center mb-4 mt-4"> Chatting System</h1>
                <form class="jumbotron pt-3" method="post">
                    <div class="form-group row ">
                        <label for="comment">Write Your Post</label>
                        <textarea id="comment" name="comment" class="form-control" rows="3" placeholder="write your post"></textarea>
                    </div>
                    <button type="button" id="submit" class="btn btn-primary" onclick="storeData()">Post</button>
                </form>
            </div>

            <div class="posts" id="contain">
                <div class="jumbotron post-container" id="post-0">
                        <div class="media">
                            <a href="https://placeholder.com"><img  class="mr-3 rounded-circle" src="http://via.placeholder.com/64x64"></a>
                            <a class="font" href="#"><i class="fas fa-trash-alt delete " id="post-0-delete"></i></a>
                            <div class="media-body">
                                <h4 class="mt-0 mb-0">Username</h4>
                                <span class="date text-muted "> Posted on 7/14/2018, 11:10:05 am</span>
                                <div class="text-justify mt-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
                                </div>
                            </div>
                        </div>
                    </div>
                <div class="jumbotron post-container" id="post-1">
                        <div class="media">
                            <a href="https://placeholder.com"><img  class="mr-3 rounded-circle" src="http://via.placeholder.com/64x64"></a>
                            <a class="font" href="#"><i class="fas fa-trash-alt delete" id="post-1-delete"></i></a>
                            <div class="media-body">
                                <h4 class="mt-0 mb-0">Username</h4>
                                <span class="date text-muted "> Posted on 7/14/2018, 11:10:05 am</span>
                                <div class="text-justify mt-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
                            </div>
                        </div>
                    </div>
                    </div>
            </div>

        </div>


    <script src="js/script.js" type="text/javascript"></script>
    </body>