簡體   English   中英

如何在jQuery Mobile 1.4.5中獲取當前頁面的URL?

[英]How do you get the current page URL in jQuery Mobile 1.4.5?

請不要將此標記為重復項。 我已經嘗試了在StackOverflow上建議的所有方法,但沒有一個起作用。 它們都給了我引用頁面的URL,而不是當前頁面的URL。 否則它們根本不起作用。 甚至window.location.href返回引用頁面URL,而不是當前頁面URL。 我正在使用jQuery Mobile 1.4.5。

例如,說我在page1.php上,然后單擊指向page1.php?getvar = 42的鏈接。 第1頁看起來像這樣:

<!doctype html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
</head>
<body><div data-role="page" data-dom-cache="false">
<a href="page1.php?getvar=42">Click Here</a>
<?php if ($_GET['getvar']=='42'): ?>
<script>
console.log(window.location.href);
console.log(document.location.href);
console.log($.mobile.activePage.data('url'));
</script>
<?php endif ?>
</div></body></html>

當我單擊上一頁中的鏈接時,我會看到控制台中的內容。 我得到:

http://hostname/page1.php
http://hostname/page1.php
/page1.php

我也嘗試過將這些調用包裝到jQuery $(document).ready()函數中的console.log()中,結果沒有變化。

<script>
$(function() {
    console.log(window.location.href);
    console.log(document.location.href);
    console.log($.mobile.activePage.data('url'));
});
</script>

如您所見,這些都不是完整的URL。 鏈接到其他文件時也是如此。 因此,它不僅會影響URL上帶有GET變量的頁面。 我希望看到/page1.php?getvar=42

我在Stack Overflow上找到了詢問相同問題的主題,但沒有一個答案對我有用。 也許他們正在使用其他版本的jQuery Mobile。 如您所見,我正在使用jQuery 1.4.5。

到目前為止,我發現的唯一解決方案是通過將data-ajax =“ false”放在父容器上來關閉jQuery mobile中頁面的Ajax加載。 但是必須有更好的方法。

(順便說一句,我需要這樣做的原因是為了可以重新加載當前頁面。但是當前所有重新加載當前頁面的嘗試都將我帶回到了引用頁面。這就是原因。)

嘗試以下功能。 我在項目中使用了這種和平的代碼,效果很好。

  var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;
    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
  };

答案是將window.location.href包裝在setTimeout()調用中,如下所示:

<script>
setTimeout(function() {
    console.log(window.location.href);
}, 0);
</script>

不過,在$(document).ready()調用內部進行包裝是行不通的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM