首页 > 解决方案 > 脚本在 HTML 中有效,但在 Scripts.js 中无效

问题描述

最近我开始开发自己的网站并提高自己的编码知识。有了这个,我已经开始遇到许多需要很长时间才能解决的问题,但到目前为止,除了这个之外,所有问题都已解决。

昨天我试图将 w3schools 中的“模态图像”添加到我创建的图片库中,除了脚本之外,一切似乎都在工作。

然后我决定将脚本隔离在一个完全独立的文件中,以确保代码确实有效,并且不是我做错了什么。一开始,当整个代码都卡在 HTML 中时,它确实起作用了,在我将 CSS 从 HTML 中分离出来之后没有引起任何问题,但是一旦我将脚本从 HTML 中取出到 Scripts.JS 中,模式就完全停止了工作.

由于我对 javascript 的了解几乎没有,我希望有人能对我的问题有所了解,因为我完全没有想法。

这是脚本。

PS:目前这是唯一不起作用的脚本,我还有其他脚本确实在同一个文件中工作,因此文件正在加载,只是这个特定的脚本不能正常工作。

// JavaScript Document

// Get the modal
var modal = document.getElementById("myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.href ="";
  captionText.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() { 
  modal.style.display = "none";
};

标签: javascript

解决方案


您的代码可能无法正常工作,因为它在 DOM 准备好之前正在运行。尝试以下操作:

document.addEventListener("DOMContentLoaded", ready);
if (document.readyState === "interactive" || document.readyState === "complete" ) ready();

function ready(){

// Get the modal
var modal = document.getElementById("myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.href ="";
  captionText.innerHTML = this.alt;
};

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() { 
  modal.style.display = "none";
};

}

推荐阅读