iT邦幫忙

0

位於html檔中的document如何從javascript 中引用?

各位先進:

請問原本在html 直接呼叫 javascript,可以透過 document存取元素,將整段javascript改放到 js檔案中,發現js檔中的document已經不是原本的document,請問在javascript中該如何access html的 document.

html如下,其中備註的 Javascript可以正確work, 將整段備註後改放到 javascript 檔案中,js 檔中的 document好像不是原來 html 的document,會報錯:

`

<p>
  <a href="index.html">index<br></a>
  <a href="page 1.html">page 1<br></a>
  <a href="page 2.html">page 2<br></a>
  <a href="page 4.html">page 4<br></a>
</p>
<!--
<script >
  var xhttp  = new XMLHttpRequest();
  var url = "test3.php";
  xhttp.open("GET", url, true);
  xhttp.onreadystatechange = phpBack;
  xhttp.send();

  function phpBack(){
    if((xhttp.readyState == 4)&&(xhttp.status == 200)){
      document.getElementById("id1").innerText = xhttp.responseText;
    }
  }
</script>
-->
<script src="page 3.js"></script>

`

page3.js的資料如下:
`
// @ts-check
var url;
var test_ajax;

window.onload = testAjax;

function testAjax() {
url = "page 3.php";
test_ajax = new XMLHttpRequest();
test_ajax.open("GET", url, true);
test_ajax.onreadystatechange = updateVar;
test_ajax.send(null);
}

function updateVar() {
if(test_ajax.readyState == 4){
var response = test_ajax.responseText;
document.getElementById("id1").innerText = response; // The line will report error, no innerText attribute
}
}

`

抱歉給大家添麻煩了?因為剛剛好像答案正確了,我也不清楚發生了什麼事.哪裡修改對了,哪裡錯了,還是... ,總之,新手問題請大家多包涵,我也說不出道理,可能要再K下書,增加基礎知識
淺水員 iT邦大師 6 級 ‧ 2020-12-05 01:43:21 檢舉
有時候會有 cache 的問題,就是後端改過 js,但是瀏覽器因為有 cache,所以並沒有更新,而是沿用舊資料。
可能是這個原因,謝謝您
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答