使用另一个

时间:2016-05-02 13:38:28

标签: javascript jquery css

我有一个包含导航链接的页面。当用户点击页面B时,我想将页面B中的内容加载到页面A的div#main-text中,但我似乎无法使其工作。我对js很新,所以对我来说很容易。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
    $("#nav_a").on("click", function(){
        $("#main_text").load("pageA.html");  
    });
    $("#nav_b").on("click", function(){
        $("#main_text").load("pageB.html");  
    });    
});
</head>
</script>

<body>
<div class="nav">
    <ul>
        <li><a id="nav_a" href="#">Page A</a></li>
        <li><a id="nav_b" href="#">Page B</a></li>
    </ul>
</div>
<div id="main_text">Page A</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

如果页面来自与包含脚本的页面相同的域并包含有效(x)html,那么它应该可以工作。

注意: Ajax无法在文件系统中运行。它需要所有文件来自Web服务器。

我个人会这样做

$(".nav a").on("click", function(e){ 
  e.preventDefault(); // cancel the click
  $("#main_text").load("page"+this.id.split("_")[1].toUpperCase()+".html"); 
});