一次在DOM中维护5个部分

Maintain five section in DOM at a time

本文关键字:维护 5个 DOM 一次      更新时间:2023-09-26

我正在创建电子书阅读器,现在我想从链接中获取电子书的部分:

 http://tmaserv.scem.uws.edu.au/chapters/?n=0   It will fetch Section number 0
 http://tmaserv.scem.uws.edu.au/chapters/?n=1   It will fetch Section number 1
 ..
 so on

章节数可从url http://tmaserv.scem.uws.edu.au/chapters获取

现在,我能够获取一个部分,但我想要的是阅读器应该在DOM中随时维护文档的5个部分。而且我们一次只能取一个section。文档加载时会先获取5个部分,然后在请求时获取其他部分。

代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>EBook</title>
<script>
var requestNum = 0;
// assume I had fetched the number of sections in varibale say sectionCount
function do_exercise () {
    var x = new XMLHttpRequest();
    // adjust the GET URL to reflect the new n value and request as before
    x.open('GET', 'http://tmaserv.scem.uws.edu.au/chapters/?n=' + requestNum, true);
    x.onreadystatechange = function() {
        if (x.readyState == 4 && x.status ==200) {
            obj = (x.responseText);
            JSON.parse(x.responseText);
            obj = JSON.parse(obj);
            document.getElementById("section1").innerHTML = obj.data;
            requestNum++;
        }
    }
    x.send(null);
}
</script>
<body>
<nav>           
    <button onclick="do_exercise();">Next section</button>      
</nav>
<section id = "section1">
</section>
</body>
</html>

我应该使用一些数组来获得5节并维护它们吗?

你想做这样的事情吗?

http://jsfiddle.net/28gtdyot/

var cacheSize = 5;
var chapters = [];
var requestNum = 0;
function fetchChapter() {
  var x = new XMLHttpRequest();
  // adjust the GET URL to reflect the new n value and request as before
  x.open('GET', 'http://tmaserv.scem.uws.edu.au/chapters/?n=' + requestNum++, true);
  x.onreadystatechange = function() {
    if (x.readyState == 4 && x.status == 200) {
      obj = (x.responseText);
      JSON.parse(x.responseText);
      obj = JSON.parse(obj);
      chapters.push(obj.data);
      if (chapters.length > cacheSize) {
        chapters.shift();
      }
      for (var i = 0; i < chapters.length; ++i) {
        document.getElementById("section" + i).innerHTML = chapters[i];
      }
    }
  }
  x.send(null);
}