0

我有以下 HTML:

    <a id="foo">Click Me</a>

    <form action="" method="post">
        <input type="submit" value="submit">
    </form>

    <script type="text/javascript">

        $(function() {
            $('#foo').click(function() {
                alert('hello');
            });
        });

    </script>

如您所见,“点击我”工作正常,直到我点击提交按钮(重新加载页面)。

如何防止这种情况发生,以便即使在提交表单后“点击我”也能按预期工作?

注意:这是我的内部内容<head>

<head>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
</head>

更新:我尝试删除

<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />head标签中,它可以工作,但是这个 CSS 文件是 Jquery Mobile 的重要组成部分。

4

2 回答 2

2

可能性很少。

您可以将属性data-ajax="false"添加到表单中。因此,您的表单将充当普通表单。没有它,jQuery Mobile 将处理表单提交,这可能是您不想要的。

<form action="" method="post" data-ajax="false">
    <input type="submit" value="submit">
</form>

其他解决方案是更改绑定单击事件的方式。而不是你的方式,你应该使用这样的现代解决方案:

$(document).on('click','#foo',function() {
    alert('hello');
});

最后一件事。除非您知道自己在做什么,否则不要使用此代码在 DOM 上绑定 click 事件:

    $(function() {
        $('#foo').click(function() {
            alert('hello');
        });
    });

与纯 jQuery 不同,jQuery Mobile 使用不同的逻辑。这是因为当文档就绪触发 jQuery Mobile 页面时,通常仍未在 DOM 中完全加载和增强。正因为如此,jQM 开发人员创建了页面事件。如果您想了解更多信息,请阅读我关于该主题的其他答案:jQuery Mobile: document ready vs page events

于 2013-05-05T19:50:13.323 回答
0

你可以改变这个:

   <input type="submit" value="submit">

为了:

   <input type="button" value="submit">

告诉我这是.. :D

于 2013-05-05T19:51:05.177 回答