我使用 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/