[英]Jquery link and URL hash
我是jQuery的新手,我真的不知道自己在做什么。 我需要協助。
我正在創建一個Web應用程序。 它有一個頁眉和頁腳,我想保留在每個頁面上,因此我決定使用jQuery將頁面加載到主要內容div中,因此每次單擊鏈接時,都不會重新加載整個頁面。
這是我用來實現此目的的方法:
<script>
$(function() {
$("a.ajax-link").on("click", function(e) {
e.preventDefault();
$("#main_content").fadeOut('fast');
$("#main_content").load(this.href);
$('html, body').animate({ scrollTop: 0 }, 0);
$("#main_content").fadeIn('fast');
});
});
</script>
並且每個鏈接:
<a class="ajax-link" id="add" href="add.php"><span class="glyphicon glyphicon-plus-sign" style="margin-top:4px;"></span><div>add</div></a>
除頁面地址外,這非常有用。 我的應用程序使用PHP,並且我需要能夠將PHP標頭添加到“ index.php#about”之類的頁面,該頁面將加載index.php頁面並在#main_content div中顯示about.php。
我嘗試了這個:
<script type="text/javascript">
$(document).ready(function(){
var id = window.location.hash;
$(id).trigger('click');
})
</script>
我可以看到選中鏈接的位置(它周圍的框),但實際上並沒有單擊它。 我不知道為什么。
預先感謝您的任何幫助!
我認為您可以獲取哈希值,添加php擴展名並進行ajax調用。
<script>
$(function() {
$("a.ajax-link").on("click", function(e) {
e.preventDefault();
// Get the hash from the URL and append .php extension
// index.php#about ==> 'about.php'
var page = window.location.hash + ".php";
//Make an ajax call using the page variable.
$("#main_content").fadeOut('fast');
$("#main_content").load(page);
$('html, body').animate({ scrollTop: 0 }, 0);
$("#main_content").fadeIn('fast');
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.