javascript - 页面加载在div中,不想为主页创建新页面

标签 javascript php jquery html

我使用 jQuery 在 div 内加载新页面,但我不想只为主页上该 div 中的内容创建一个页面。我的脚本如下:

<script type="text/javascript">
    $(document).ready(function() {
        $(".navigation").on("click", function(){  
            $("#content").load($(this).attr("page"));
            return false;
        });
    });
</script>

一切加载正常

<div id="content"></div>

但我的导航部分的结构是让 HOME 成为一个选择。

<nav id="menu">
    <a href="" title="" page="home.php" class="navigation">Home</a>
    <a href="" title="" page="about.php" class="navigation">About</a>
</nav>

有没有办法让脚本加载原始页面“内容”div 中的所有内容,或者让“主页”按钮成为索引页面的实际链接会更容易?

如果我将其更改为,一切仍然有效

<a href="index.php" title="">Home</a>

我只是不喜欢加载整个页面,而不是单击网站上的其他按钮并仅加载内容。

最佳答案

来自jQuery docs :

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

所以你可以这样做:

<script type="text/javascript">
    $(document).ready(function() {
        $(".navigation").on("click", function(){  
            var page = $(this).data("page");
            if(page == "index.php"){                    
                 //Load only element with id content from index.php
                 $("#content").load(page + " #content"); 
            } else{
                $("#content").load(page);
            }
            return false;
        });
    });
</script>

<nav id="menu">
    <a href="" title="" data-page="index.php" class="navigation">Home</a>
    <a href="" title="" data-page="about.php" class="navigation">About</a>
</nav>
PS。正如adeneo指出的那样,您不应该使用无效属性,因此我将您的属性更改为数据属性。

关于javascript - 页面加载在div中,不想为主页创建新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27643091/

相关文章:

javascript - 在嵌套 promise 链中捕获错误的更简洁方法?

javascript - 从 JavaScript 调用 jQuery 函数

javascript - 无法从前端应用程序调用 Algolia 分析 API?

php - 如何计算PHP中的对角线差?

php - 检查数组中的值是否已存在于数据库中+将数组添加到数据库

php - TCPDF:图像无法在 PDF 中正确显示

jquery - jVectorMap:如何通过坐标动态添加标记?

javascript - 一个 .js 加载所有 .js 和 .css

jQuery - 选择上一个元素链接

javascript - 不显示 div,因为传递的参数(值)的行为就像字符串而不是 div id