简体   繁体   中英

how to add a pre made div using javascript on button click

I have a webpage that looks like this

在此处输入图片说明 I want it like that every time the save note is pressed a new card with updated title and description appears on the right.

This is the html code I wrote

<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>

The card is the one with id=card in the code and that is the thing I want new every-time.

This is the javascript I wrote

 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();

When a new note is saved it appears on the left side. I don't understand how when that card on the left side is clicked that notes title and description occupies the places on the right.

The simplest solution IMO would be generate the HTML by looping over the Notes array.

1) This function iterates (using map ) over the array and returns HTML using a template literal (what's between the back-ticks):

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) And you can add it to the card panel like this:

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

DEMO

Edit

In order to solve the next part of the question move all the node selections outside of the functions, and then add an event listener to the cards container.

 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> 

Hope that helps.

There is a JavaScript function called createElement() that allows you to create and assign a HTML element into a variable. Once the element is created, just append the content to it and then append the element to a HTML element.

For example:

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);

You can also use createTextNode instead of textContent.

Traverse the listOfNodes and create card and append it to the div. Whenever you click savenote the card will be appeared. Here is the working demo.

 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> 

Replace your anchor template (your "a ...id="card" code) with an unordered list like so:

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

Then utilize DOM's appendChild() method: https://www.w3schools.com/jsref/met_node_appendchild.asp

So your JS code will be something like this

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM