簡體   English   中英

使用document.getElementById無法正常工作

[英]Using document.getElementById not working

我有2個html文件和一個外部js文件。 第一個html文件將打印出圖像及其名稱。 這些圖像是可單擊的,它們的名稱存儲在外部js文件中的2個數組中。 單擊圖像時,我想在外部js文件中獲得單擊圖像的名稱,然后在第二個html文件中打印該圖像。

第一個html文件

<body>
   <p>
   <script type = "text/javascript">
      for (var i = 0; i < pic.length; i++) {
          document.write("<a href=\"specify.html\"><img id=\"image\" src = \" " + pics[i] + "\"></a>" + "<br>");
          document.write(name[i] + "<br>");
      }
  </script>
  <p>
</body>

外部js文件,假定數組不為空。

var pic = new Array();
var name = new Array();
var image = document.getElementById("image").src;

第2個html,specify.html

document.write("<img src = \" " + image + "\">" + "<br>");

image變量的值是不確定的。 我不知道自己在做什么錯,請幫忙。

首先,正如@ Aziz-Saleh所指出的那樣,您不應在頁面中重復ID。 嘗試在ID上添加一個數字。

其次,我不確定我是否知道要執行的操作,但是看來您想在一個頁面中設置一個變量,然后在另一個頁面中打印該變量而不將其存儲在其他位置。

如果我是對的,您可以按照自己的方式來做。 似乎您不了解HTML頁面或HTTP如何工作。

每個HTML頁面就像一個不同的應用程序。 每次頁面加載時,都會解析並執行外部js文件。 加載多少次或對變量進行何種修改都無所謂。 加載新頁面時,所有內容都會恢復為默認值。 因此,即使您在第一頁中設置了圖像文件,在第二頁中也未定義圖像文件,直到為其分配值為止。

嘗試這個:

<body>
   <p>
   <script type = "text/javascript">
      for (var i = 0; i < pic.length; i++) {
          document.write('<a class="images" href="specify.html"><img src="' + pics[i] + '\" data-index="' + i + '"></a><br>' + name[i] + '<br>');
      }

      document.addEventListener('click', function(e) {
          var index = this.getAttribute('data-index');
          if (index !== undefined) {
               document.location = 'specify.html#' + index;
               e.preventDefault();
          }
      }, false);
  </script>
  <p>
</body>

specify.html ...

var index = document.location.hash.substr(1);
document.write("<img src = \" " + pics[index] + "\">" + "<br>");

基本上,我正在做的是獲取所單擊圖像的索引,並請求第二個頁面將此索引作為URL的一部分傳遞。 在第二頁中,我從哈希部分(位於#后面的url部分)中獲取該索引,然后編寫與該索引對應的圖像。

正如其他人所指出的那樣,document.write()很老。 我建議您閱讀有關DOM頁面生命周期的信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM