【问题标题】:How can I change the body content onclick some button如何更改正文内容 onclick some button
【发布时间】:2020-04-05 23:03:32
【问题描述】:

我正在使用 JQuery 来加载我网站的导航栏和正文,并且我想在单击导航栏中的某个按钮时更改正文内容 我可以使用 JavaScript 来做到这一点吗?我该怎么办?

请我一直在寻找解决方案,但我没有找到任何东西。 在此先感谢

html

 <header>
      <script>
        $(function () {
          $("header").load("./dist/includes/navbar.html");
        });
      </script>
    </header>
    <!-- END of Section NavBar  -->
    <main>
      <script>
        $(function () {
          $("main").load("./dist/includes/home.html");
        });
      </script>
    </main>
    <!-- Section Footer  -->
    <footer class="footer">
      <script>
        $(function () {
          $("footer").load("./dist/includes/footer.html");
        });
      </script>
    </footer>

当我单击 id="nav-link" 的按钮时,我想更改加载的 home.html 文件

这是截图

【问题讨论】:

  • 请不要将代码和错误消息作为图像发布,而是以代码格式的文本发布,因为我们都不能复制、粘贴和运行图像。有关这方面的更多信息,请在提问时查看 SO 上的Why may I not upload images of code?。另请查看How to Ask,了解更多现场最佳实践。
  • 您需要准确单击哪个按钮并更改代码?
  • 好的,我会添加代码
  • 这能回答你的问题吗? Change content of div - jQuery
  • @ElmanHuseynov 我想在单击 id="nav-link" 的按钮时更改加载了 JQuery 的 home.html

标签: javascript jquery html local pageload


【解决方案1】:

考虑下面的代码。

$(function() {
  // Load content
  $("header").load("./dist/includes/navbar.html");
  $("main").load("./dist/includes/home.html");
  $("footer").load("./dist/includes/footer.html");

  // Prpgram Events
  $("header").on("click", "button", function(ev) {
    console.log("Nav Button was clicked");
    $("main p").append("<a href='#'>New Page</a>");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Section NavBar  -->
<header></header>
<!-- END of Section NavBar  -->
<main></main>
<!-- Section Footer  -->
<footer class="footer"></footer>
<!-- END of Section Footer  -->

我们使用 jQuery 加载内容。由于 ready 上的 DOM 中不存在该内容,我们将使用 .on() 将事件回调委托给现在已加载的项目。

所以如果在header中加入如下的HTML,例如:

<button>Show Link</button>

点击后会执行匿名回调并将链接追加到main中。

查看更多:https://api.jquery.com/on/

最好使用服务器端脚本来构造 HTML。它们中的许多具有包含特性或功能,可以在将页面发送到浏览器之前将页面添加到输出中,以便客户端可以预先处理所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多