如何在Javascript中编辑多个Div元素的文本内容?

时间:2018-10-13 10:53:26

标签: javascript

我5个月前开始学习编程(JavaScript),我需要您的帮助。它是关于一个在线书店(具有添加/删除和搜索功能),问题是我正在尝试制作一个允许用户进行编辑的功能有关书籍的信息,例如书籍名称,价格,说明等。使用Bootstrap模式。 我尝试了所有event.target for-loop等。.但是它不起作用。我提出了解决方案(请参见下面的代码),但是我必须为每个元素设置不同的ID,这是个坏主意。 你能帮忙吗? 我预先感谢大家

https://codepen.io/Sam_2018/pen/QZMPmX

  

var form = document.getElementById("addBook");
form.addEventListener("submit", addCard);
var cardList = document.getElementById("books");

function addCard(e) {
    e.preventDefault();

    // delete Button------------------------
    var icon = document.createElement("i");
    icon.className = "far fa-trash-alt";
    var delBtn = document.createElement("button");
    delBtn.className = "btn-sm btn-outline-danger m-1 delete";
    delBtn.appendChild(icon);

    //h5 and P-------------------
    var headline = document.createElement("h5");
    headline.className = "card-title";
    var bookName = document.getElementById("bookName").value;
    localStorage.setItem("title", bookName);
    console.log(localStorage.getItem("title"));

    var title = document.createTextNode(bookName);
    headline.appendChild(title);
    var para = document.createElement("p");
    para.className = "card-text";
    var bookDescription = document.getElementById("message-text").value;
    var description = document.createTextNode(bookDescription);
    para.appendChild(description);
    var div1 = document.createElement("div");
    div1.className = "card-body";
    div1.appendChild(headline);
    div1.appendChild(para);

    //ul and li--------------
    var li = document.createElement("li");
    li.className = "list-group-item";
    var autor = document.getElementById("autor-name").value;
    var autorName = document.createTextNode(autor);
    li.appendChild(autorName);
    var ul = document.createElement("ul");
    ul.className = "list-group list-group-flush";
    ul.appendChild(li);

    // buy button-----------------------
    var buyBtn = document.createElement("button");
    buyBtn.className = "btn btn-warning mb-2";
    var price1 = document.getElementById("price").value;
    var bookPrice = document.createTextNode("Buy Now for" + " " + price1 + " €");
    buyBtn.appendChild(bookPrice);
    //----------------------

    var generalDiv = document.createElement("div");
    generalDiv.className = "card m-2 text-center col-3";
    generalDiv.id = "sam";
    generalDiv.style = "width: 18rem;";
    generalDiv.appendChild(delBtn);
    generalDiv.appendChild(div1);
    generalDiv.appendChild(ul);
    generalDiv.appendChild(buyBtn);
    cardList.appendChild(generalDiv);
    delBtn.addEventListener("click", deleteListElement);
    var addBtn = document.getElementById("btnContainer");
    addBtn.parentNode.insertBefore(generalDiv, addBtn);

}


var del = document.getElementsByClassName("delete");
for (var i = 0; i < del.length; i++) {
    del[i].addEventListener("click", deleteListElement);
}
function deleteListElement() {
    //remove the parent of button from its grand parent
    this.parentNode.parentNode.removeChild(this.parentNode);
}


function searchBook() {
    var input, filter, section, divs, a, i;
    input = document.getElementById("search");
    filter = input.value.toUpperCase();
    section = document.getElementById("books");
    divs = section.getElementsByTagName("div");
    for (var i = 0; i < divs.length; i++) {
        a = divs[i].getElementsByTagName("h5")[-0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            divs[i].style.display = "";
        } else {
            divs[i].style.display = "none";

        }
    }
}

editBook.addEventListener("submit", bas);
function bas(e) {
    e.preventDefault();
    var newtxt = document.getElementById("bookName").value;
    document.getElementById("sam2").textContent = newtxt;
    console.log(newtxt);
}
#search{
    margin: auto;
    margin-top: 30px;
}
#addBtn1{
    width: 100px;
    height:100px;
    border-radius: 50%;
    border:3px solid skyblue;
}
<!doctype html>
<html lang="en">

<head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU"
        crossorigin="anonymous">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B"
        crossorigin="anonymous">
</head>

<body>

    <input id="search" type="text" class="form-control  col-3 " onkeyup="searchBook()" placeholder="Search for Books...">

    <div class="row d-flex m-5 bg-dark justify-content-center " id="books">

        <div id="sam" class="card m-2 text-center col-3">
            <button class="btn-sm btn-outline-danger m-1 delete "><i class="far fa-trash-alt"></i></button>
            <button id="editor" type="button" class="btn-sm btn-outline-success m-1 " data-toggle="modal" data-target="#exampleModal"
                data-whatever="@mdo">Edit </i></button>
            <img class="card-img-top" src="/saveus2.jpg" alt="Card image cap">
            <h5 id="sam2" class="card-title">SAVE US</h5>
            <p class="card-text">Ruby steht unter Schock: Sie wurde vom
                Maxton-Hall-College suspendiert. Und
                das
                Schlimmste: Alles deutet darauf hin, dass niemand ...</p>
            <!--   <div onClick="this.contentEditable='true';">
                    lorem ipsum dolor lorem ipsum dolorlorem ipsum dolor
                </div> -->
            <h4>Mona Kasten</h4>
            <button class="btn btn-warning mb-2 ">Buy Now for 29.99 €</button>

        </div>
        <div id="sam" class="card m-2 text-center col-3">
            <button class="btn-sm btn-outline-danger m-1 delete "><i class="far fa-trash-alt"></i></button>
            <img class="card-img-top" src="/download (1).jpeg" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">Das Orakel</h5>
                <p class="card-text">Ruby steht unter Schock: Sie wurde vom Maxton-Hall-College suspendiert. Und
                    das
                    Schlimmste: Alles deutet darauf hin, dass niemand ...</p>
            </div>
            <ul class="list-group list-group-flush">
                <li class="list-group-item">Daphne Niko</li>

            </ul>

            <button class="btn btn-warning mb-2">Buy Now for 39.99 €</button>
        </div>
        <div id="sam" class="card m-2 text-center col-3">
            <button class="btn-sm btn-outline-danger m-1 delete "><i class="far fa-trash-alt"></i></button>
            <img class="card-img-top" src="/download.jpeg" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">Der Outsider</h5>
                <p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Mollitia hic, velit ab
                    harum autem soluta ex ...</p>
            </div>
            <ul class="list-group list-group-flush">
                <li class="list-group-item">Stephen King</li>
            </ul>
            <button class="btn btn-warning mb-2">Buy Now for 29.99 €</button>
        </div>
        <div id="sam" class="card m-2 text-center col-3">
            <button class="btn-sm btn-outline-danger m-1 delete "><i class="far fa-trash-alt"></i></button>
            <img class="card-img-top" src="/61iAgN-A3cL._SY346_.jpg" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">Die Stadt der Träumenden Bücher</h5>
                <p class="card-text">Ruby steht unter Schock: Sie wurde vom Maxton-Hall-College suspendiert. Und
                    das
                    Schlimmste: Alles deutet darauf hin, dass niemand ...</p>
            </div>
            <ul class="list-group list-group-flush">
                <li class="list-group-item">Walter Moers</li>
            </ul>
            <button class="btn btn-warning mb-2">Buy Now for 29.99 €</button>
        </div>
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">New message</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Book Name:</label>
                                <input type="text" class="form-control" id="bookName">
                            </div>
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Autor Name:</label>
                                <input type="text" class="form-control" id="autor-name">
                            </div>
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Price:</label>
                                <input type="text" class="form-control" id="price">
                            </div>
                            <div class="form-group">
                                <label for="message-text" class="col-form-label">Book Description:</label>
                                <textarea class="form-control" id="message-text"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <form id="addBook" class="form-inline ">
                            <input id="myBtn" type="submit" class="form-control m-2 btn btn-warning" value="Add">
                        </form>
                        <form id="editBook" class="form-inline ">
                            <input id="myBtn" type="submit" class="form-control m-2 btn btn-success" value="edit">
                        </form>
                        <!-- <button id="editBtn" type="button" class="btn btn-success m-1  " data-toggle="modal"
                            data-target="#exampleModal" data-whatever="@mdo">edit</i></button> -->
                    </div>
                </div>
            </div>
        </div>

        <div id="btnContainer" class="  align-self-center ">
            <button id="addBtn1" type="button" class="btn btn-outline-success m-5 " data-toggle="modal" data-target="#exampleModal"
                data-whatever="@mdo"><i class="fas fa-plus"></i>

            </button></div>
    </div>


    <script src="/main.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em"
        crossorigin="anonymous"></script>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

var form = document.getElementById("addBook");
form.addEventListener("submit", addCard);
var cardList = document.getElementById("books");

function addCard(e) {
    e.preventDefault();

    // delete Button------------------------
    var icon = document.createElement("i");
    icon.className = "far fa-trash-alt";
    var delBtn = document.createElement("button");
    delBtn.className = "btn-sm btn-outline-danger m-1 delete";
    delBtn.appendChild(icon);

    //h5 and P-------------------
    var headline = document.createElement("h5");
    headline.className = "card-title";
    var bookName = document.getElementById("bookName").value;
    localStorage.setItem("title", bookName);
    console.log(localStorage.getItem("title"));

    var title = document.createTextNode(bookName);
    headline.appendChild(title);
    var para = document.createElement("p");
    para.className = "card-text";
    var bookDescription = document.getElementById("message-text").value;
    var description = document.createTextNode(bookDescription);
    para.appendChild(description);
    var div1 = document.createElement("div");
    div1.className = "card-body";
    div1.appendChild(headline);
    div1.appendChild(para);

    //ul and li--------------
    var li = document.createElement("li");
    li.className = "list-group-item";
    var autor = document.getElementById("autor-name").value;
    var autorName = document.createTextNode(autor);
    li.appendChild(autorName);
    var ul = document.createElement("ul");
    ul.className = "list-group list-group-flush";
    ul.appendChild(li);

    // buy button-----------------------
    var buyBtn = document.createElement("button");
    buyBtn.className = "btn btn-warning mb-2";
    var price1 = document.getElementById("price").value;
    var bookPrice = document.createTextNode("Buy Now for" + " " + price1 + " €");
    buyBtn.appendChild(bookPrice);
    //----------------------

    var generalDiv = document.createElement("div");
    generalDiv.className = "card m-2 text-center col-3";
    generalDiv.id = "sam";
    generalDiv.style = "width: 18rem;";
    generalDiv.appendChild(delBtn);
    generalDiv.appendChild(div1);
    generalDiv.appendChild(ul);
    generalDiv.appendChild(buyBtn);
    cardList.appendChild(generalDiv);
    delBtn.addEventListener("click", deleteListElement);
    var addBtn = document.getElementById("btnContainer");
    addBtn.parentNode.insertBefore(generalDiv, addBtn);

}


var del = document.getElementsByClassName("delete");
for (var i = 0; i < del.length; i++) {
    del[i].addEventListener("click", deleteListElement);
}
function deleteListElement() {
    //remove the parent of button from its grand parent
    this.parentNode.parentNode.removeChild(this.parentNode);
}


function searchBook() {
    var input, filter, section, divs, a, i;
    input = document.getElementById("search");
    filter = input.value.toUpperCase();
    section = document.getElementById("books");
    divs = section.getElementsByTagName("div");
    for (var i = 0; i < divs.length; i++) {
        a = divs[i].getElementsByTagName("h5")[-0];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
            divs[i].style.display = "";
        } else {
            divs[i].style.display = "none";

        }
    }
}

editBook.addEventListener("submit", bas);
function bas(e) {
    e.preventDefault();
    var newtxt = document.getElementById("bookName").value;
    document.getElementById("sam2").textContent = newtxt;
    console.log(newtxt);
}

$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget);
  var title = button.data('title');
  var modal = $(this)
  modal.find('.modal-body input#bookName').val(title)
})
#search{
    margin: auto;
    margin-top: 30px;
}
#addBtn1{
    width: 100px;
    height:100px;
    border-radius: 50%;
    border:3px solid skyblue;
}
<!doctype html>
<html lang="en">

<head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU"
        crossorigin="anonymous">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B"
        crossorigin="anonymous">
</head>

<body>

    <input id="search" type="text" class="form-control  col-3 " onkeyup="searchBook()" placeholder="Search for Books...">

    <div class="row d-flex m-5 bg-dark justify-content-center " id="books">

        <div id="sam" class="card m-2 text-center col-3">
            <button class="btn-sm btn-outline-danger m-1 delete "><i class="far fa-trash-alt"></i></button>
            <button id="editor" type="button" class="btn-sm btn-outline-success m-1 " data-toggle="modal" data-target="#exampleModal"
                data-title="SAVE US">Edit </i></button>
            <img class="card-img-top" src="/saveus2.jpg" alt="Card image cap">
            <h5 id="sam2" class="card-title">SAVE US</h5>
            <p class="card-text">Ruby steht unter Schock: Sie wurde vom
                Maxton-Hall-College suspendiert. Und
                das
                Schlimmste: Alles deutet darauf hin, dass niemand ...</p>
            <!--   <div onClick="this.contentEditable='true';">
                    lorem ipsum dolor lorem ipsum dolorlorem ipsum dolor
                </div> -->
            <h4>Mona Kasten</h4>
            <button class="btn btn-warning mb-2 ">Buy Now for 29.99 €</button>

        </div>
        <div id="sam" class="card m-2 text-center col-3">
            <button class="btn-sm btn-outline-danger m-1 delete "><i class="far fa-trash-alt"></i></button>
            <img class="card-img-top" src="/download (1).jpeg" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">Das Orakel</h5>
                <p class="card-text">Ruby steht unter Schock: Sie wurde vom Maxton-Hall-College suspendiert. Und
                    das
                    Schlimmste: Alles deutet darauf hin, dass niemand ...</p>
            </div>
            <ul class="list-group list-group-flush">
                <li class="list-group-item">Daphne Niko</li>

            </ul>

            <button class="btn btn-warning mb-2">Buy Now for 39.99 €</button>
        </div>
        <div id="sam" class="card m-2 text-center col-3">
            <button class="btn-sm btn-outline-danger m-1 delete "><i class="far fa-trash-alt"></i></button>
            <img class="card-img-top" src="/download.jpeg" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">Der Outsider</h5>
                <p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Mollitia hic, velit ab
                    harum autem soluta ex ...</p>
            </div>
            <ul class="list-group list-group-flush">
                <li class="list-group-item">Stephen King</li>
            </ul>
            <button class="btn btn-warning mb-2">Buy Now for 29.99 €</button>
        </div>
        <div id="sam" class="card m-2 text-center col-3">
            <button class="btn-sm btn-outline-danger m-1 delete "><i class="far fa-trash-alt"></i></button>
            <img class="card-img-top" src="/61iAgN-A3cL._SY346_.jpg" alt="Card image cap">
            <div class="card-body">
                <h5 class="card-title">Die Stadt der Träumenden Bücher</h5>
                <p class="card-text">Ruby steht unter Schock: Sie wurde vom Maxton-Hall-College suspendiert. Und
                    das
                    Schlimmste: Alles deutet darauf hin, dass niemand ...</p>
            </div>
            <ul class="list-group list-group-flush">
                <li class="list-group-item">Walter Moers</li>
            </ul>
            <button class="btn btn-warning mb-2">Buy Now for 29.99 €</button>
        </div>
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">New message</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Book Name:</label>
                                <input type="text" class="form-control" id="bookName">
                            </div>
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Autor Name:</label>
                                <input type="text" class="form-control" id="autor-name">
                            </div>
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Price:</label>
                                <input type="text" class="form-control" id="price">
                            </div>
                            <div class="form-group">
                                <label for="message-text" class="col-form-label">Book Description:</label>
                                <textarea class="form-control" id="message-text"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <form id="addBook" class="form-inline ">
                            <input id="myBtn" type="submit" class="form-control m-2 btn btn-warning" value="Add">
                        </form>
                        <form id="editBook" class="form-inline ">
                            <input id="myBtn" type="submit" class="form-control m-2 btn btn-success" value="edit">
                        </form>
                        <!-- <button id="editBtn" type="button" class="btn btn-success m-1  " data-toggle="modal"
                            data-target="#exampleModal" data-whatever="@mdo">edit</i></button> -->
                    </div>
                </div>
            </div>
        </div>

        <div id="btnContainer" class="  align-self-center ">
            <button id="addBtn1" type="button" class="btn btn-outline-success m-5 " data-toggle="modal" data-target="#exampleModal"
                data-whatever="@mdo"><i class="fas fa-plus"></i>

            </button></div>
    </div>


    <script src="/main.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em"
        crossorigin="anonymous"></script>
</body>

</html>

希望这会有所帮助。