高级使用jQuery load()函数

时间:2012-02-15 12:12:56

标签: jquery

我正在阅读一本关于Javascript和jQuery的书,并使用其中一个示例创建了一个带有3个标签的ajax网页: 这是代码:(主页面和第一个选项卡,其他两个选项卡相同)

load.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>News Headlines</title>
<link href="../_css/site.css" rel="stylesheet">
<style>
#newslinks li {
    display: inline-block;
    margin-right: 20px;
}
#newslinks li a {
    padding: 5px 10px; 
    background-color: white;
    color: black !important;
    text-decoration: none;  
}
#newslinks li a:hover {
    background-color: rgb(110,138,195);
    color: white !important;    
}
#headlines .newsItem {
    margin-top: 10px;
    padding: 20px;
    border: 1px solid white;    
}
</style>
<script src="../_js/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function() {
  $('#newslinks a').click(function() {
     var url=$(this).attr('href');
     $('#headlines').load(url + ' #newsItem');
     return false;
  }); //end click

}); // end ready
</script>
</head>
<body>
<div class="wrapper">
    <div class="header">
        <p class="logo">JavaScript <i>&</i> jQuery <i class="mm">The<br>Missing<br>Manual</i></p>
    </div>
    <div class="content">
        <div class="main">
            <h1>News Headlines</h1>
            <ul id="newslinks">
            <li><a href="today.html">Today&#8217;s News</a></li>
    <li><a href="yesterday.html">Yesterday&#8217;s News</a></li>
    <li><a href="lastweek.html">Last Week&#8217;s News</a></li>
            </ul>
            <div id="headlines"></div>
        </div>
    </div>
    <div class="footer">
        <p>JavaScript &amp; jQuery: The Missing Manual, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p>
    </div>
</div>
</body>
</html>

today.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>News Headlines</title>
<link href="../_css/site.css" rel="stylesheet">
</head>
<body>
<div class="wrapper">
    <div class="header">
        <p class="logo">JavaScript <i>&</i> jQuery <i class="mm">The<br>Missing<br>Manual</i></p>
    </div>
    <div class="content">
        <div class="main">
            <div id="newsItem">
            <h2 class="shadowLine">Today&#8217;s News</h2>
            <h3>Labore et dolore</h3>
  <p>Quis nostrud exercitation ut labore et dolore magna aliqua. Sed do eiusmod tempor incididunt cupidatat non proident, duis aute irure dolor. Consectetur adipisicing elit, velit esse cillum dolore ut aliquip ex ea commodo consequat. Ullamco laboris nisi ut enim ad minim veniam. Ut enim ad minim veniam, lorem ipsum dolor sit amet, ut labore et dolore magna aliqua.</p>
  <h3>Quis nostrud exercitation</h3>
  <p> ut labore et dolore magna aliqua. Sed do eiusmod tempor incididunt cupidatat non proident, duis aute irure dolor. Consectetur adipisicing elit, velit esse cillum dolore ut aliquip ex ea commodo consequat. Ullamco laboris nisi ut enim ad minim veniam. Ut enim ad minim veniam, lorem ipsum dolor sit amet, ut labore et dolore magna aliqua.</p>
  </div>
        </div>
    </div>
    <div class="footer">
        <p>JavaScript &amp; jQuery: The Missing Manual, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p>
    </div>
</div>
</body>
</html>

现在我正在尝试添加另一个页面而不是today.html但到目前为止还没有结果。 问题是我要添加的新页面比today.html复杂得多,所以我需要一些帮助。 当然新的tab1.html页面可以自行运行 这是代码。

tab1.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>News Headlines</title>
    <link href="../_css/site.css" rel="stylesheet">
    <!--  Add fancyBox2 css-->
    <link rel="stylesheet" href="../fancybox2/source/jquery.fancybox.css" type="text/css" media="screen" />

    <style>
        .image {
            float: left;
            padding: 10px;
            border: solid 1px white;
            margin: 0 30px 30px 0;
        }
        .image:hover {
            border-color: red;
            background-color: rgb(204,204,204);
        }


    </style>

    <script src="../_js/jquery-1.7.1.min.js"></script>
    <!-- Add fancyBox2 script-->
    <script type="text/javascript" src="../fancybox2/source/jquery.fancybox.pack.js"></script>

    <script>
        $(document).ready(function() {
            var URL = "http://api.flickr.com/services/feeds/groups_pool.gne";
            var ID = "35034346867@N01";
            var jsonFormat = "&format=json&jsoncallback=?";

            var ajaxURL = URL + "?id=" + ID + jsonFormat;
            $.getJSON(ajaxURL,function(data)
                    {
                        $('h1').text(data.title);
                        $.each(data.items,function(i, photo)

                                {
                                    var photoHTML = '<span class="image">';
                                    photoHTML += '<a class="fancybox" rel="gallery1" href="' + photo.media.m.replace('_m', '_b') + '">';
                                    photoHTML += '<img src="' + photo.media.m.replace('_m', '_s') + '"></a>';


                                    $('#photos').append(photoHTML);

                                }


                        );//end each

                        $('#photos .fancybox').fancybox(
                                {
                                    openEffect:'none',
                                    closeEffect:'none'
                                }
                        );
                    }

            );//end get JSON


        }); // end ready
    </script>
</head>
<body>
<div class="wrapper">
    <div class="header">
        <p class="logo">JavaScript <i>&</i> jQuery <i class="mm">The<br>Missing<br>Manual</i></p>
    </div>
    <div class="content">
        <div class="main">
            <div id="newsItem">
                <h1>Flickr Images</h1>
                <div id="photos"></div>
                <br class="clearLeft">
            </div>
        </div>
    </div>
    <div class="footer">
        <p>JavaScript &amp; jQuery: The Missing Manual, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p>
    </div>
</div>
</body>
</html>

site.css文件位于here,有关如何安装fancybox2的说明,请访问:http://fancyapps.com/fancybox/

问题是如何在不复制load.html中的所有javascript代码的情况下将tab1嵌入到加载中?

1 个答案:

答案 0 :(得分:0)

我会从$.get()更改为$.load()并手动解析页面以获取javascript。

$(document).ready(function() {
  $('#newslinks a').click(function(e) {
    e.preventDefault(); // replaces return false
    var url=$(this).attr('href');
    var $content = $('#headlines');
    $.get(url).done(function(html){
      var outHTML = html;
      // replace all script tags with divs that have a class of iscript
      outHTML = outHTML.replace(/<script/ig, "<div class='iscript'").replace(/<\/script/ig, '</div');
      // parse outHTML as a jQuery-wrapped html fragment
      outHTML = $(outHTML);
      // select and detach all script divs and store in variable
      var scripts = outHTML.filter('div.iscript').add(outHTML.find(.iscript)).detach();
      // append the news item to content
      $content.html(outHTML.find("#newsItem"));
      scripts.each(function(){
        var $this = $(this), s = document.createElement("script");
        // prevent loading jQuery twice, optional and can be modified removed
        if ($this.attr('src') == "../_js/jquery-1.7.1.min.js") {
          // continue to next script
          return true;
        }

        if ($this.attr('src') != "") {
          s.src = $this.attr('src');
        } else {
          s.nodeValue = $this.text();
        }
        $content[0].appendChild(s);
      });  
    });
  });
});

此外,我建议使用某种ajax缓存。

var ajaxCache = {};
$('#newslinks a').click(function(e) {
  e.preventDefault();
  var url = $(this).attr('href');
  if (!ajaxCache[url]) {
    ajaxCache[url] = $.get(url);
  }
  ajaxCache[url].done(function(html){
    /*... code from within done function above ...*/
  });
});