0

我正计划使用 JQM 制作一个简单的移动 Web 应用程序,但我在让这个简单的功能正常工作时遇到了问题:当我点击一些链接(不是全部)时,我希望能够首先处理一些数据,然后根据该结果,有时继续链接操作(我喜欢整个转换和 ajax 的东西),有时不。

重要的部分是我想保留正常的 JQMobile 转换和链接的东西,只是有时会阻止它们(例如用于验证和类似的事情)。

我尝试过:return false、preventDefault(并与 stopPropagation 结合使用)和 data-ajax="false",但没有一个起作用,它们都重定向了。

有人可以告诉我在 JQMobile 中的正确方法吗?以防万一它很重要:我正在使用锚链接,使用来测试。

提前谢谢你,詹妮弗。

已解决:在下面添加了答案。

4

2 回答 2

2

您可以尝试click在要阻止默认行为的链接上设置事件。

在下面的示例中,我们将一个类添加special_link到我们想要在被重定向到另一个页面之前对其进行特殊处理的链接。

当我们单击“特殊”链接时,我们会检查是否遵循给定条件,然后再决定将用户重定向到另一个页面。

重定向(包含所有转换内容)到另一个页面(page_2在我们的示例中)是手动完成的,使用以下代码:

$.mobile.changePage( "#page_2", {
  transition: "slide",
});

有关该方法的更多信息$.mobile.changePage,您可以查看在线文档:

http://api.jquerymobile.com/jQuery.mobile.changePage/

在以下示例中,如果您1在文本输入中键入 a,您将不会被重定向。否则,您将更改页面。


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>

<script>
    $(function() {

        // Setting the click event for our special link
        $(".special_link").click(function() {

            // IF SOME CONDITION THEN... (Here, if we typed a 1 in the text input)
            if($('#my_value').val()=='1') {

                // We do not change page
                alert("We stay where we are");

            } else { 

                // We change page. In this example: page 2
                $.mobile.changePage( "#page_2", {
                transition: "slide",      // You can define the transition 
                                          // you want + other parameters

                });
            }
        });
    });
</script>

</head>
<body>
    <!-- PAGE 1 -->
    <div data-role="page" id="page_1">
        <div data-role="content">
            <h1>Page 1</h1>

                <input type="text" id="my_value"/>

                <!-- A SPECIAL LINK -->
                <a href="" class="special_link">Special link</a>

        </div>
    </div>

    <!-- PAGE 2 -->
    <div data-role="page" id="page_2">
        <div data-role="content">
            <h1>Page 2</h1>
            <a href="#page_1">Go back to page 1</a>
        </div>
    </div>
</body>
</html>

我希望这有帮助。如果您有任何问题,请告诉我。

于 2013-07-02T04:51:33.433 回答
0

好的,所以我想出了一个相当不错的方法来做到这一点,而不会让它感觉像一个杂物。我只是要避免使用标签,而是使用按钮,这样我通常会拦截它们,如果我想转换,我使用 changePage JQM 方法。奇迹般有效。感谢Littm的提示,我希望这对将来的其他人有用。

于 2013-07-03T22:11:29.913 回答