【问题标题】:jQuery pushState load content, different URLsjQuery pushState 加载内容,不同的 URL
【发布时间】:2025-11-23 04:45:01
【问题描述】:

我在尝试从http://html5.gingerhost.com/ 重新创建演示时遇到了一些问题。我会尽量把情况描述清楚:

在我的页面上有,点击它会触发:

  • 将浏览器的 URL 栏更改为 mysite.tld/index 的 pushState 事件
  • 一个 getJSON 调用,它加载一个随机 url 并把它而不是当前的

当用户点击加载的随机url时,pushState事件不会触发,浏览器会跟随随机url...这不是我想要的。我想继续触发 pushState 事件并继续加载随机 url。

类似这样的:

  • 点击索引
    • 加载索引 2 并替换索引
      • CLICK INDEX2 (此处中断。它会加载真实页面)
        • LOAD INDEX3 和 REPLACE INDEX2 (我要到这里)

如果我不清楚,我深表歉意。我对自己的 jQuery 技能不是很有信心。

你有什么建议吗?

这里是源代码:

<!DOCTYPE html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        $('a').click(function(e) {
            href = $(this).attr("href");

            loadContent(href);

            history.pushState('', 'New URL: '+href, href);
            e.preventDefault();
        });
    });

    function loadContent(url){
        $.getJSON("load.php", {pid: url}, function(json) {
            $.each(json, function(key, value){
                $(key).html(value);
            });
        });         
    }   
</script>
</head>

<body>
    <div>
        <a href="index">Go to: index</a>
    </div>
    <p></p>
</body>
</html>

load.php

<?php $i = rand(0,10); ?>
{
"div":"<a href='<?php echo $_GET['pid'].$i; ?>'>Go to: <?php echo $_GET['pid'].$i; ?></a>",
"p":"This is the page for <?php echo $_GET['pid']; ?>"
}

【问题讨论】:

    标签: jquery json pushstate


    【解决方案1】:

    那是因为

    $('a').click(function(e) { …
    

    仅适用于执行此行时 DOM 中的 a 元素。您稍后将其替换为 另一个 a 元素,它不会被此捕获。

    请改用.on,例如像这样:

    $(document).on("click", "a", function(e) { …
    

    【讨论】: