jQuery从PHP加载数据,然后它消失了,为什么?


jQuery loads the data from PHP but then it disappears, why?

我搜索了一下,看看这里是否有类似的帖子,如果有人发现它很抱歉重复。

所以我的困境是:

给出下面的代码,为什么我返回的数据加载然后消失?

CSS

#contentbg{
   background-image: url(../images/jp_01.jpg);
   background-repeat: no-repeat;
   background-position: top;
   position: absolute;
   width: 755px;
   height: 629px;
}
#content{
   position: relative;
}

JS

function getHome(){ 
    $.post("php/functions.php?s=home",
     function(data) {
     $('#content').html(data);   
   });
};

<div id="contentbg">
    <div id="content"></div>
</div>
<ul id="navlist">
     <li id="home"><a href="index.php" onClick="getHome();" title="Home"></a></li>
</ul>
PHP

function displayHome($home){
    if(isset($home)){
        $home = '<img src="images/home.jpg" alt="Home" width="755" height="630" />';
        return $home;
    }
}
if (isset($_GET['s'])) {
    switch ($_GET['s']) {
        case "home": 
            echo displayHome($_GET['s']);
            break;
        }
}

我知道数据被加载,如果我改变JS如下所示:

function getHome(){ 
    $.post("php/functions.php?s=home",
     function(html) {
     alert("Data Loaded: " + html);
   });
};

问题是,当你点击链接时,你没有取消标准动作,所以发生的是你点击,javascript被执行,然后index.php被加载。

你需要从你的getHome函数中返回false来解决这个问题。

function getHome(){ 
   $.post("php/functions.php?s=home",
     function(data) {
     $('#content').html(data);   
   });
   return false;
}

当你已经在使用jquery时,你也可以摆脱内联javascript并使用如下函数:

$("#home a").click(function(event) {
  event.preventDefault();
  $.post("php/functions.php?s=home",
     function(data) {
     $('#content').html(data);   
  });
);

这也保证了标准事件(点击链接)被第一行取消。

我没有看到任何项目与id #content在你的HTML,你确定它存在吗?

我假设#content是在HTML结构中定义的:

$('#content').load('php/functions.php?s=home');

现在也尝试删除#content { position: relative; },以防内容"跳跃"一旦加载到文档

在你的html中似乎没有"content"div。
此外,使用

$("#content").load("url");

,因为不需要使用$。