首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JS:替换不是替换信息

JS:替换不是替换信息
EN

Stack Overflow用户
提问于 2021-01-25 17:40:10
回答 1查看 73关注 0票数 1

我正在编写一个动作,在按下按钮后,平台上的游戏“控制台”或"pc“会显示出来。我希望当" pc“的按钮被按下时,所有的pc游戏都会显示出来。当“控制台”按钮被按下后,所有的"pc“游戏被移除,然后所有的”控制台“游戏被附加

按钮的代码如下:

代码语言:javascript
复制
<button class="btn btn-success" type="submit" onclick="searchPC()">PC</button>
<button class="btn btn-success" type="submit" onclick="searchCon()">Console</button>

这两个按钮的函数代码是相似的;

代码语言:javascript
复制
function searchPC() {
  $("search").replaceWith(`<div></div>`);

  axios
    .get(`${baseUrl}/game/PC`)
    .then((response) => {
      const posts = response.data;
      console.log(posts);
      posts.forEach((post) => {
        const postPHtml = `
          <div class="card sm-6" style="margin-top: 2rem;">
              <div class="card-body ">
                  <p class="card-text">${post.title}</p>
              </div>
              <div class="card-footer text-muted">
                  <p>${post.description}</p>
                  <p>SGD$${post.price}</p>
              </div>
              <div class="card-footer text-muted">
                  <a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
              </div>
          </div>
          `;

        $("#search").replaceWith(postPHtml);
      });
    })
    .catch((error) => {
      console.log(error);
    });
}

我尝试的是用一个空的div替换任何信息,然后添加所需的信息,但是,它仍然显示较旧的信息(参考上文,即使按下“控制台”后,"pc“仍然显示。

此外,我还有一张以上的卡片要添加,即有超过2套游戏机和电脑游戏的信息

包含js的原始文件为:

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Friendbook</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body class='bg-dark'>
    <div class="container-fluid bg-dark">
        <div class="">
            <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
                <a class="navbar-brand" href="/">
                    <div>
                        <img src="http://localhost:8082/images/image.jpg" alt="logo" style="width:40px;" id="logo">
                    </div>
                </a>
                <a class="nav-link" href="/">Home</a>
                <button class="btn btn-success" type="submit" onclick="searchPC()">PC</button>
                <button class="btn btn-success" type="submit" onclick="searchCon()">Console</button>
            </nav>
            <nav class="navbar navbar-expand-sm bg-dark navbar-dark mt-1">
                <form class="form-inline ml-2" action="/action_page.php">
                    <input class="form-control" id='searchP' type="text" placeholder="Search by Price">
                    <button class="btn btn-success" type="submit">Search</button>
                </form>
                <form class="form-inline ml-2" action="/action_page.php">
                    <input class="form-control" id='searchN' type="text" placeholder="Search by Name">
                    <button class="btn btn-success" type="submit">Search</button>
                </form>
            </nav>

            <div class="row" style="margin-top: 2rem;">
            </div>

        </div>
        <div class="card" style="margin-top: 2rem;">
            <div class="card-body col-md-10">
                <h4 class='title '>Search Games</h4>
                <div id="search" class="container-fluid md-6 sm-6">
                </div>
            </div>
        </div>
        <div class="card" style="margin-top: 2rem;">
            <div class="card-body col-md-10">
                <h4 class='title '>All Games</h4>
            </div>
        </div>
        <div class="row" style="margin-top: 2rem;">

            <div class="col-md-11 col-xs-12 ml-5">
                <div id="posts" class="container-fluid md-6 sm-6">
                </div>

            </div>

        </div>
    </div>
    <footer class='bg-dark p-3'>
        <div class='ml-2 mt-2'>
            <form>
                <button class="btn btn-success" type="submit" onclick="logout()">logout</button>
            </form>
        </div>

    </footer>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        const baseUrl = "http://localhost:8081";
        const token = localStorage.getItem("token");
        const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));

        if (token === null /* || isNaN(loggedInUserID) */) {
            window.location.href = "/login/";
        } else {
            axios.get(`${baseUrl}/gameall/all`)
                .then((response) => {
                    const posts = response.data;
                    console.log(posts)
                    posts.forEach((post) => {
                        const postHtml = `
                    <div class="card sm-6" style="margin-top: 2rem;">
                        <div class="card-body ">
                            <p class="card-text">${post.title}</p>
                        </div>
                        <div class="card-footer text-muted">
                            <p>${post.description}</p>
                            <p>SGD$${post.price}</p>
                        </div>
                        <div class="card-footer text-muted">
                            <a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
                        </div>
                    </div>
                    `;

                        $("#posts").append(postHtml);
                    });
                })
                .catch((error) => {
                    console.log(error);
                });

            /*
            axios.get(`${baseUrl}/game/console/`)
            .then((response) => {
                const posts = response.data;
                console.log(posts)
                posts.forEach((post) => {
                    const postHtml = `
                <div class="card sm-6" style="margin-top: 2rem;">
                    <div class="card-body ">
                        <p class="card-text">${post.title}</p>
                    </div>
                    <div class="card-footer text-muted">
                        ${post.description}
                    </div>
                    <div class="card-footer text-muted">
                        <a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
                        <p class="card-text">${post.price}</p>
                    </div>
                </div>
                `;

                    $("#posts").append(postHtml);
                });
            })
            .catch((error) => {
                console.log(error);
            });*/

            //acts as addpost api
            $("#create-post-form").submit((event) => {
                // prevents the page from refreshing
                event.preventDefault();

                const requestBody = {
                    text_body: $("#create-post-form-body").val(),
                    fk_poster_id: loggedInUserID
                };

                // create the post
                axios.post(`${baseUrl}/posts/`, requestBody)
                    .then((response) => {
                        // reset form value.
                        $("#create-post-form-body").val("");

                        // fetch the post with the returned postID
                        axios.get(`${baseUrl}/posts/${response.data.postID}`)
                            .then((response) => {
                                const post = response.data;
                                const postHtml = `
                    <div class="card sm-6" style="margin-top: 2rem;">
                        <div class="card-body sm-6">
                            <p class="card-text">${post.text_body}</p>
                        </div>
                        <div class="card-footer text-muted">
                            ${post.created_at}
                        </div>
                    </div>
                    `;
                                $("#posts").append(postHtml);
                            })
                            .catch((error) => {
                                console.log(error);
                            });
                    });
            });
        }
        function logout() {
            localStorage.removeItem('token')
            localStorage.removeItem('role')
            localStorage.removeItem('id')
        }
        function searchPC() {

            axios.get(`${baseUrl}/game/PC`)
                .then((response) => {
                    const posts = response.data;
                    console.log(posts)
                    posts.forEach((post) => {
                        const postPHtml = `
                    <div class="card sm-6" style="margin-top: 2rem;">
                        <div class="card-body ">
                            <p class="card-text">${post.title}</p>
                        </div>
                        <div class="card-footer text-muted">
                            <p>${post.description}</p>
                            <p>SGD$${post.price}</p>
                        </div>
                        <div class="card-footer text-muted">
                            <a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
                        </div>
                    </div>
                    `;
                        $("#search").appendChild(postPHtml);
                    });
                })
                .catch((error) => {
                    console.log(error);
                });
        }
        function searchCon() {
            axios.get(`${baseUrl}/game/console`)
                .then((response) => {
                    const posts = response.data;
                    posts.forEach((post) => {
                        const postCHtml = `
                    <div class="card sm-6" style="margin-top: 2rem;">
                        <div class="card-body ">
                            <p class="card-text">${post.title}</p>
                        </div>
                        <div class="card-footer text-muted">
                            <p>${post.description}</p>
                            <p>SGD$${post.price}</p>
                        </div>
                        <div class="card-footer text-muted">
                            <a class="nav-link" href="/gamesinfo/${post.gameid}">Home</a>
                        </div>
                    </div>
                    `;

                        $("#search").appendChild(postCHtml);
                    });
                })
                .catch((error) => {
                    console.log(error);
                });
        }

    </script>

</body>

</html>```
EN

回答 1

Stack Overflow用户

发布于 2021-01-25 18:13:25

我觉得你需要使用**html(htmlString) **

描述:设置匹配元素集合中每个元素的HTML内容

替换$("#search").replaceWith(postPHtml);

使用$("#search").html(postPHtml);

请参阅:https://api.jquery.com/html/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65882226

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档