内联脚本在表单提交后停止工作

时间:2013-05-05 19:39:43

标签: jquery html5 jquery-mobile

我有以下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>

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

如何防止这种情况发生,以便即使在提交表单后“Click me”也能正常工作?

注意:以下是<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的重要组成部分。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你可以改变这个:

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

有关:

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

告诉我这是......:D

相关问题