AJAX 加载方法和切换

AJAX load method and toggle

首先对不起我的菜鸟! :-( 我目前正在尝试 AJAX jQuery load() 方法来为我的导航链接加载 html 页面内容。为此,我创建了一个空的 div 标签有一个 id,我正在相应地替换它:

HTML 主网页:

 <!--nav links-->:
<a href="#" id="index">Home</a>
<a href="#" id="news">News</a>
<a href="#" id="events"></a>

<!-- Main Container to be replaced-->
<div id="#pageContent"></div>

JQuery:

 $("#index").click(function() {
    $("#pageContent").load("home.html", function (response, status, xhr) {  // (selector).load(url, data, function(response, status, xhr))
        if (status == "error") {                                            // function is an optional callback method that runs when request is completed.
            var msg = "Sorry but there was an error: ";                     // response = contains result data from request
            $("#error").html(msg + xhr.status + " " + xhr.statusText);      // status = contains status of request (error, success, etc)
        }                                                                   //  xhr = contains XMLHttpp Request object
    });    
});

但是,#index 内容还有一个切换按钮,如果按下该按钮,它将重定向到另一个 div 的特定部分 - #news 也被 ajax 调用。它的目的是转到特定的新闻文章(例如,我有一个包含 10 篇文章的列表,当有人在#index 部分按下 "read more" 按钮时,它将在#news 部分加载第 5 篇文章)。我为此创建了 JS 函数,当我静态加载页面时它可以工作:

function showNews(newsToGo) {
            window.location.assign(newsToGo);
        }


        //-News Box 1-//
        document.getElementById('news-redirect1').addEventListener("click", function(){
                showNews("news.html#news-post-1");
        });

现在,我不知道如何让它在 AJAX 中工作。如果我保留 JS,它只会加载 "bare" div。谁能指出我正确的方向?

我想你可以尝试这样的事情。如果您的 "global" 页面 JS 文件未随每个单独的页面一起加载,您可以在其上添加导航功能。

例如,你可以有这样的东西(前提是我正确理解你的问题)。

function showNews(newsToGo) {
    window.location.assign(newsToGo);

    $('#pageContent')
        .empty()    // you could call empty, or you could clone the current content
                    // so you wouldn't have to reload it via ajax again
        .load(newsToGo, function(response, status, xhr){
            // do your news stuff here, like inits or whatever :)
        });
}