實現innerHTML中javascript的運行,從而使的頁面各個模組間更好的互動,和資料共用.

來源:互聯網
上載者:User

實現innerHTML中javascript的運行,從而使的頁面各個模組間更好的互動,和資料共用.

在參考前人的一些做法後,採用了一些變通方式,和添加一些額外標記,來較好的實現innerHTML中javascript的運行,從而使的頁面各個模組間更

好的互動,和資料共用.

先看下面的例子:

<html>
<head>
</head>
<script>
 var title = "hello";
 var time = 0;
 var author = "vickenyang";
 var email = "ycg01@software.nju.edu.cn";
</script>
<body>
 <div id="div_1">
 <SPAN style="display: none">hidden</SPAN>
 hehe
  <!--bs-->
  <script>
   document.write("first");
  </script>
  <!--es-->
  這是第一個頁面!
  <br>
  <!--bs-->
  <script>
   time++;
   document.write(title+time+author);
   //alert(time);
   document.write("<br>---------------");
  </script>
  <!--es-->
  <input type="text" name="test" value="test">
 </div>

<script>
function refreshDiv(div)
{
 var html = "";
 function changediv()
 {
  var oldwrite = document.write;
  var oldwriteln = document.writeln;
  document.write = function(str)
  {
   html += str;
  }
  document.writeln = function (str)
  {
   html += str + "\n";
  }
  var htmlTmp = div.innerHTML;
  //ie預設大寫,添加為支援firefox,美中不足,會替換所有script值,如果只是ie應用,可登出此行
  htmlTmp = htmlTmp.replace(/script/gi,"SCRIPT");
  //alert(htmlTmp);
  var pos_1 = 0;
  var pos_2 = 0;
  pos_1 = htmlTmp.indexOf("<SCRIPT>",pos_1);
  while(pos_1 != -1)
  {
   html += htmlTmp.substring(pos_2,pos_1);
   var pos_3 = htmlTmp.indexOf("</SCR"+"IPT>",pos_1); 
   html += htmlTmp.substring(pos_1,pos_3+"<-SCRIPT>".length);
   pos_2 = pos_1+"<SCRIPT>".length;
   eval(htmlTmp.substring(pos_2,pos_3));
   pos_2 = htmlTmp.indexOf("<!--es-->",pos_3);
   pos_1 = htmlTmp.indexOf("<SCRIPT>",pos_1+1);
  }
  html += htmlTmp.substring(pos_2,htmlTmp.length);
  document.write = oldwrite;
  document.writeln = oldwriteln;
 }
 eval("changediv();");
 div.innerHTML = html;
}

function change()
{
 refreshDiv(document.getElementById('div_1'));
}
function change2()
{
 document.write("over");
}
</script>
<input type="button" value="change" onclick="change();">
<input type="button" value="change2" onclick="change2();">
</body>
</html>

步驟:
1.在div的第一行加上<SPAN style="display: none">hidden</SPAN>(不這麼做,ie會忽略首位的js)
2.在div中每一個js的前後加上<!--bs--><!--es-->標記.

原理:代碼會告訴你的.如果你有更好的方法,請郵件聯絡,共同探討.

補:

function refreshDiv(div)
{
 var html = "";

如果在特殊的應用中用到遞迴調用,可以將此處的html 定義為全域變數,這樣,保證遞迴重新整理時候,顯示的是最後一個頁面.(如,你想在ajax中,非同步load資料,在回呼函數中指定重新整理div的時候就可能用到)

下面的例子中有具體的應用:一個基於ajax的,個性網頁構建雛形

http://bbs.nju.edu.cn/file/Y/ycg/obj.rar 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.