如何在按钮上单击以使用javascript添加预制div

时间:2018-09-17 16:47:34

标签: javascript html

我有一个看起来像这样的网页

enter image description here 我希望每次按下保存笔记时,都会在右侧显示新的卡片,其标题和说明均已更新。

这是我编写的html代码

<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-4 rightLine">
            <h1 class="bottomLine">Note List</h1>
            <div class="active-cyan-3 active-cyan-4 mb-4">
                <input class="form-control" type="text" placeholder="Search" aria-label="Search">
            </div>
            <div id ="cards"></div>
        </div>
        <div class="col-md-8">
            <h1 class="bottomLine">Note</h1>
            <div class="active-cyan-3 active-cyan-4 mb-4">
                <input class="form-control" id="title" type="text" placeholder="Enter title here" aria-label="Search">
            </div>
            <div class="active-cyan-3 active-cyan-4 mb-4 bottomLine">
                <textarea class="form-control" id="description" rows="15" placeholder="Enter descirption here"></textarea>
            </div>
            <div>
                <button type="button" id="removenote" class="btn btn-outline-danger">Remove Note</button>
                <button type="button" id="savenote" class="btn btn-outline-success" onclick="x.saveNote()">Save Note</button>
                <button type="button" id="addnote" class="btn btn-outline-primary" onclick="x.addNote()">Add Note</button>
            </div>
        </div>
    </div>
</div>

该卡是代码中id = card的卡,这就是我每次都想要的东西。

这是我写的javascript

 class Note {
    constructor(name, description) {
        this.name = name;
        this.description = description;
    }
}

class NoteComponent {
    constructor() {
        this.listOfNotes = [];
    }

    saveNote() {
        let title = document.getElementById("title").value;
        let description = document.getElementById("description").value;
        let currentNote = new Note(title, description);
        this.listOfNotes.push(currentNote);

        getCardHTML(this.listOfNotes);

        this.listOfNotes.forEach((arrayItem) => {
            console.log('name is ' + arrayItem.name + ' description is ' + arrayItem.description);
        });
    }

    addNote() {
        let title = document.getElementById("title").value = "";
        let description = document.getElementById("description").value = "";
    }


    filterList(noteList, Query) {}
}

/*when the specific note card clicked the title and description places will be populated*/
function showNote(){
    console.log('the onclcik worked fine');
}

function getCardHTML(arr) {
    let divOfCards = document.getElementById('cards');
    while (divOfCards.firstChild) {
        divOfCards.removeChild(divOfCards.firstChild);
    }
    for (let i = 0; i < arr.length; i++) {
        let div = document.getElementById("cards");
        let anchor = document.createElement("div");
        anchor.className = "list-group-item list-group-item-action flex-column align-items-start";
        let innerDiv = document.createElement("div");
        innerDiv.className = "d-flex w-100 justify-content-between";
        let divHeading = document.createElement("h5");
        divHeading.className = "mb-1";
        divHeading.innerHTML = arr[i].name;
        let divPara = document.createElement("p");
        divPara.className = "mb-1";
        divPara.innerHTML = arr[i].description;
        //anchor.href = "#";
        anchor.onclick = showNote();

        innerDiv.appendChild(divHeading);
        anchor.appendChild(innerDiv);
        anchor.appendChild(divPara);
        div.appendChild(anchor);
    }
}

let x = new NoteComponent();

保存新笔记后,它会出现在左侧。我不明白当单击左侧的卡片时,注释标题和描述会占据右侧的位置。

4 个答案:

答案 0 :(得分:0)

最简单的IMO解决方案是通过遍历Notes数组来生成HTML。

1)此函数在数组上迭代(使用map),并使用template literal(在反引号之间)返回HTML:

function getCardHTML(arr) {

  // Array.map returns a new array
  return arr.map(({ name, description }) => {

    // In this case the array has a number of elements containing
    // HTML strings
    return `<h5 class="card-title">${name}</h5><p class="card-text">${description}</p>`;

  // which is joined into one HTML string before it's returned
  }).join('');
}

2)您可以像这样将其添加到卡面板中:

const cards = document.querySelector('.card-body');
cards.innerHTML = getCardHTML(listOfNotes);

DEMO

修改

为了解决问题的下一部分,将所有节点选择移到函数之外,然后将事件侦听器添加到card容器。

class Note {
  constructor(name, description) {
    this.name = name;
    this.description = description;
  }
}

class NoteComponent {
  constructor() {}
  filterList(noteList, Query) {}
}

const listOfNotes = [];
const title = document.getElementById('title');
const description = document.getElementById('description');

const save = document.getElementById("savenote");
save.addEventListener("click", saveNote, false);

const cards = document.querySelector('.cards');
cards.addEventListener('click', showNote, false);


function getCardHTML(arr) {
  return arr.map(({ name, description }, i) => {
    return `<div data-id="${i}" class="card"><h5>${name}</h5><p>${description}</p></div>`;
  }).join('');
}

function saveNote() {
  let currentNote = new Note(title.value, description.value);
  listOfNotes.push(currentNote);
  cards.innerHTML = getCardHTML(listOfNotes);
}

function showNote(e) {
  const t = e.target;
  const id = t.dataset.id || t.parentNode.dataset.id;
  title.value = listOfNotes[id].name;
  description.value = listOfNotes[id].description;
}
<div class="cards"></div>
<div>
  <input id="title" type="text" placeholder="Enter title here" aria-label="Search">
</div>
<div>
  <textarea id="description" rows="15" placeholder="Enter descirption here"></textarea>
</div>
<div>
  <button type="button" id="removenote">Remove Note</button>
  <button type="button" id="savenote">Save Note</button>
  <button type="button" id="addnote">Add Note</button>
</div>

希望有帮助。

答案 1 :(得分:0)

有一个名为createElement()的JavaScript函数,该函数可用于创建HTML元素并将其分配给变量。 创建元素后,只需将内容附加到元素,然后将元素附加到HTML元素即可。

例如:

var body = document.getElementsByTagName('body');
var title = document.getElementById("title").value;
var description = document.getElementById("description").value;
var div = document.createElement("div");
var h1 = document.createElement("h1");
var p = document.createElement("p");
// assign values to elements
h1.textContent = title;
p.textContent = description;
// append elements to div
div.appendChild(h1);
div.appendChild(p);
// append div to body
body.appendChild(div);

您也可以使用createTextNode代替textContent。

答案 2 :(得分:0)

遍历listOfNodes并创建card并将其附加到div。只要您单击保存便笺,便会显示该卡。这是工作示例。

class Note{
    constructor(name, description) {
        this.name = name;
        this.description = description;
      }
}

let listOfNotes = [];

class NoteComponent{
    constructor(){}

    filterList(noteList,Query){}
}

document.getElementById("savenote").addEventListener("click", function(){
  
    let title = document.getElementById("title").value;
    let description = document.getElementById("description").value;
    let currentNote = new Note(title,description);
    listOfNotes.push(currentNote);
    var newNode = document.getElementById("card");
    listOfNotes.forEach((arrayItem) => {
      console.log(arrayItem.name);
      
      var name = document.createElement("h5");
      var nameText = document.createTextNode(arrayItem.name);
      name.appendChild(nameText);
      
      var description = document.createElement("p");
      var desc = document.createTextNode(arrayItem.description);
      description.appendChild(desc);
      
      var card_body = document.createElement("div");
      card_body.className = "card_body";
      
      card_body.appendChild(name);
      card_body.appendChild(description);
      
      var card = document.createElement("div");
      card.className = "card";
      
      card.appendChild(card_body);
      
      var aTag = document.createElement("a");
      aTag.className="custom-card";
      aTag.setAttribute("id", "card");
      aTag.appendChild(card);
      
      var cardDiv = document.getElementById("card");
      cardDiv.appendChild(aTag);
      
      
    });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="container-fluid">
        <div class="row">
            <div class="col-md-4 rightLine">
                <h1 class="bottomLine">Note List</h1>
                <div class="active-cyan-3 active-cyan-4 mb-4">
                    <input class="form-control" type="text" placeholder="Search" aria-label="Search">
                </div>
              <div id="card">
                <a href="#" id="card" class="custom-card">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Card title</h5>
                            <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
                        </div>
                    </div>
                </a>
              </div>
            </div>
            <div class="col-md-8">
                <h1 class="bottomLine">Note</h1>
                <div class="active-cyan-3 active-cyan-4 mb-4">
                    <input class="form-control" id="title" type="text" placeholder="Enter title here" aria-label="Search">
                </div>
                <div class="active-cyan-3 active-cyan-4 mb-4 bottomLine">
                    <textarea class="form-control" id="description" rows="15" placeholder="Enter descirption here"></textarea>
                </div>
                <div>
                    <button type="button" id="removenote" class="btn btn-outline-danger">Remove Note</button>
                    <button type="button" id="savenote" class="btn btn-outline-success">Save Note</button>
                    <button type="button" id="addnote" class="btn btn-outline-primary">Add Note</button>
                </div>
            </div>
        </div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
    </div>
</body>
</html>

答案 3 :(得分:0)

将锚定模板(您的“ a ... id =“ card”代码)替换为无序列表,如下所示:

<ul id="cards"></ul>

然后利用DOM的 appendChild()方法: https://www.w3schools.com/jsref/met_node_appendchild.asp

所以您的JS代码将是这样

document.getElementById("savenote").addEventListener("click", function(){
    let title = document.getElementById("title").value;
    let description = document.getElementById("description").value;
    let currentNote = new Note(title,description);
    let listedCard = document.createElement("LI");
    listOfNotes.push(currentNote);

    listOfNotes.forEach((arrayItem) => {
        console.log('name is ' + arrayItem.name + ' description is ' + arrayItem.description);
    });

    // New code
    let listedCard = document.createElement("LI");
    let cardAnchor = document.createElement("A");
    //...
    listedCard.appendChild(cardAnchor);
    //...
    // The rest of your HTML code for the <a...id="card"> goes here. Little tedious
    // Finally append the listedCard to the UL
    let cardList = document.getElementById("cards");
    cardList.appendChild(listedCard);
});