我一直在本地机器上玩引导程序,试图建立一个网站,到目前为止一切顺利。虽然我遇到了一个奇怪的问题,但我不确定它是否与引导程序或其他原因有关。
在我的网站上,我有一个导航栏和多个 btn 链接
下面是菜单链接的示例
<a href="?Page=home">Home</a>
她是BTN链接的考试者
<a class="btn btn-info" href="?Page=development">Read More</a>
除了标题和我的身体之外,还有一个空的div
<div class="my-body"></div>
这样做的目标是有一个基于 get 变量加载内容的页面,该变量将其传递给 get 函数以加载如下所示的页面
<?php
$page_to_load = 'home';
if(isset($_GET['Page'])){
if(strlen($_GET['Page'])>0){
$page_to_load = $_GET['Page'];
}
}
?>
那么我的JavaScript看起来像这样
$.get('/pages/<?php echo $page_to_load; ?>.php', function(response){
$('.my-body').html(response);
});
到目前为止,上述所有代码都按预期工作,但后来我想,如果您单击链接时整个页面没有重新加载并且它只是获得了新内容,那不是很好吗?这就是我头痛的地方,我基本上使用以下 JavaScript 困扰我的是,有时它似乎适用于导航栏链接而不是按钮链接。我确定我错过了一些东西,或者我拥有它的方式根本行不通。
var _baseLink = 'http://localhost/'
$(document).ready(function(){
$('a').click(function(){
try{
var _href = $(this).attr('href');
if(_href.indexOf('#')==-1){
var _url = document.URL;
_url = _url.split('?')[0];
if(_url.indexOf('default.php')<0){
_url = _baseLink + 'default.php';
}
var _title = document.title;
var Url = _url + _href;
//it only sometimes logs this message
console.log('rntitle:' + _title + 'rnhref:' + _href + 'rn_url:' + _url + 'rnUrl:' + Url);
//change url
window.history.pushState({"urlPath": Url}, _title, Url);
//change page content
//this could be a bad ajax request but never get it this far.
$.get(_baseLink + 'pages/' + _href.replace("?Page=", "") + '.php', function(data){ $('.my-body').html(data); });
//prevent page reload
return false;
}
}catch ($ex){
window.console && console.log($ex);
}finally{
return false;
}
});
});
任何帮助或指导将不胜感激
var _baseLink = 'http://localhost/'
/* try to put the script at the bottom of the page
to avoid using document ready */
$(document).ready(function(){
$('a').click(function(e) {
e.preventDefault(); // use this
try{
var _href = $(this).attr('href');
if(_href.indexOf('#')==-1){
var _url = document.URL;
_url = _url.split('?')[0];
if(_url.indexOf('default.php')<0){
_url = _baseLink + 'default.php';
}
var _title = document.title;
var Url = _url + _href;
//it only sometimes logs this message
console.log('rntitle:' + _title + 'rnhref:' + _href + 'rn_url:' + _url + 'rnUrl:' + Url);
//change url
window.history.pushState({"urlPath": Url}, _title, Url);
//change page content
//this could be a bad ajax request but never get it this far.
$.get(_baseLink + 'pages/' + _href.replace("?Page=", "") + '.php', function(data){ $('.my-body').html(data); });
//prevent page reload
return false;
}
}catch ($ex){
window.console && console.log($ex);
}finally{
return false;
}
});
});
谢谢jstice4all使用e.preventDefault()
使我的原始代码工作,并且由于使其工作,我能够看到问题。 我的问题是通过 ajax 加载的内容专门具有带有 .btn
引导类的锚点,并且该类不是问题,而是我在它们实际加载到页面上之前绑定了新的点击事件。 所以我重构了我的代码在初始 ajax 调用后绑定单击事件,然后在每次后续请求后重新绑定我的内容div 中定位点的单击事件。感谢您的提示,希望对您有所帮助。