duanpiangeng8958
duanpiangeng8958
2014-01-19 16:57
浏览 28

JavaScript包括另一个文件

I have this bit of code:

var curState = 'Agenda';

function switchState(newState) {
  curState = newState;
}

function Inbox() {
  switchState('Inbox');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Inbox.";
}

function Friends() {
  switchState('Friends');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Friends.";
}

function Agenda() {
  switchState('Agenda');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Agenda.";
}

function List() {
  switchState('List');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Book List.";
}

function News() {
  switchState('News');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the News.";
}

function Notes() {
  switchState('Notes');
  document.getElementById("u-content").innerHTML = "Currently, you're viewing the Notes.";
}

Of course the text displayed is a test and I will change it. The point is, I'd have to put a lot of text into these 'statuses' of a menu and to simply type it out in here is not very handy, especially if there are changes to be made later on. Therefore I'd like to know how to add different forms of files in JavaScript, or let them display using JavaScript, like a *.php file.

Is there somebody who knows how to do such a thing? I've searched quite a lot on the internet, but was unable to find something useful to me, except document.getElementById().innerHTML = "";

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyu0852
    douyu0852 2014-01-19 17:07
    已采纳

    There are three easy ways to do this:

    Variant A: Get your innerHTML from the server via an AJAX call - something like

    function News() {
      switchState('News');
      document.getElementById("u-content").innerHTML = "Please wait for News to load.";
      //start AJAX call here
    }
    
    function AJAXcallOnSuccess() {
      document.getElementById("u-content").innerHTML = //Result text from AJAX call;
    }
    

    Variant B: Have your text delivered in the original page, but not shown. Something like

    <blah>
    ... 
    <div style="display: none;" id="newsPlaceHolder">
    This is the text for the news item
    </div>
    ...
    </blah>
    
    function News() {
      switchState('News');
      document.getElementById("u-content").innerHTML = document.getElementById("newsPlaceHolder").innerHTML
    }
    

    Variant B leads to the easiest Variant C: Have all DIVs ready in the page, but only show one at a time.

    var activeDiv = null;
    
    function News() {
      switchState('News');
      if (activeDiv) activeDiv.style.display='none';
      activeDiv=document.getElementById("u-content-news");
      activeDiv.style.display='block';
    }
    
    点赞 评论

相关推荐