【问题标题】:Using jquery load function in combination with forms结合表单使用jquery加载功能
【发布时间】:2020-07-26 12:39:18
【问题描述】:

目前正在开发一个新网站,并希望使用 jQuery 的 load() 函数将来自不同 html 页面的内容加载到我的主页中。

load() 工作正常。这是我当前的代码。 加载内容的 Main.html 页面:

<div id="answer"></div>

带有load() 函数的Javascript:

$(document).ready(function() {
    $("#answer").load( "game1content.html #p1Answer");

game1content.html 加载内容:

<div id="p1Answer">
    <p>Some text</p>
    <form id="answer1Form">
        <select name="answer1" id="answer1">
            <option value=""></option>
            <option value="1">Website 1</option>
            <option value="2">Website 2</option>
            <option value="3">Website 3</option>
            <option value="4">Website 4</option>
        </select>
        <button id="submitButton">SUBMIT</button>
    </form>
</div>

所以它会正确地将 html 加载到答案 div 中。完美。

现在的挑战是,当我提交已加载的表单时,它会刷新页面。当我在 main.html 文件中有 game1content 内容时,而不是使用 load() 它不会重新加载并且工作正常。但如果我使用load() 函数,它会重新加载并更改网址。

这是我的提交功能:

$( "#answer1Form" ).submit(function(e) {
    e.preventDefault();
    console.log ("clicked");
});

我试过用谷歌搜索这个问题,但找不到太多。另外,尝试将.submit 更改为onclick 等,但结果相同。有什么想法吗?

【问题讨论】:

  • e.stopPropagation();返回假;

标签: html jquery ajax


【解决方案1】:

这是因为当您调用 .load 时,它会获取页面内容并添加 DOM 元素但不会将它们绑定到事件,因此 form 的行为应该如此,刷新页面。

为了防止表单刷新,您应该像在 game1content.html 在添加 DOM 元素之后一样听 .submit()

像这样:

$("#answer").load( "game1content.html #p1Answer", function() {
  $( "#answer1Form" ).submit(function(e) {
    e.preventDefault();
    console.log("clicked");
  });
});

【讨论】:

  • 太棒了!非常感谢您的帮助,让我开心!
  • 任何时候 :) 祝你好运。
猜你喜欢
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多