【问题标题】:Change pages on click?单击时更改页面?
【发布时间】:2016-06-29 18:07:24
【问题描述】:

我有两个 html 文件,index.html 和 page2.html,当用户使用 javascript 或 Jquery 单击按钮时,我想用 index.html 替换 page2.html。 我正在尝试将页面加载到正文中,但是当我单击按钮时,它会使页面变为空白。

function caloriesTopTab(){
  $('#button1').click(function(){
    $("body").load('page2.html');
  });
}

module.exports = caloriesTopTab;

【问题讨论】:

  • 为什么不直接使用标准链接?至于您的实际问题,请检查控制台是否有错误。这可能有任何原因无法正常工作,从不包括 jQuery 到 HTML 文件的路径不正确。
  • 不熟悉 .load 但认为它在这里被滥用了.. 试试 window.location = 'page2.html'; ?
  • 控制台出现什么错误?
  • 我相信您不需要将这些东西包装在一个函数中?可以使用$(document).ready()来发起按钮点击捕捉
  • 你也可以看到这个问题:stackoverflow.com/questions/2238368/…

标签: javascript jquery


【解决方案1】:

您可以使用全局 location.replace 函数:

$("#button1").click(function() {
    location.replace("/page2.html");
});

虽然这在功能上等同于使用带有“/page2.html”href 属性的 HTML <a> 标记,而根本不使用 javascript,这将是更简单且因此更好的方法。如果您希望页面在后台加载并且仅在加载时更改 DOM,我想您可以使用 AJAX 请求:

var ajaxRunning = false;
$("#button1").click(function() {
    if (!ajaxRunning) { // don't send two requests at once
        ajaxRunning = true;
        $.ajax("/page2.html", {
            method: "GET",
            dataType: "html"
        }).done(function(html) {
            ajaxRunning = false;
            document.write(html);
        });
    }
});

这样做绝对没有真正的好处(而且成本更高),除非“page2.html”是一个部分 HTML 文件,您将只使用它来更新部分 DOM(使用 jQuery htmltext 函数,而不是 document.write)。

因此,除非您有令人信服的理由引入 javascript,否则只需使用 HTML <a> 标记,如下所示:

<a href="/page2.html">
    <button id="button1">Click me!</button>
</a>

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 2013-06-13
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多