javascript - 脚本在 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";
};
解决方案
您的代码可能无法正常工作,因为它在 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";
};
}
推荐阅读
- sparql - SPARQL - 使用纬度和经度从 DBpedia 获取城市名称
- c# - EFCore Postgres 时间戳丢失刻度精度
- reactjs - 反应堆和重新渲染的焦点问题
- javascript - 为什么控制台上只显示最后一个函数?
- c# - 如何一次性或手动或本地安装 C# 依赖项以在没有 Internet 连接的情况下离线工作 VS-code?
- node.js - 生成迁移时如何从秘密存储中动态添加 TypeOrm 配置?
- asp.net-core - Blazor InputText:有条件地呈现属性
- angular - 在 Angular 7 应用程序中获取 net::ERR_HTTP2_PROTOCOL_ERROR
- arrays - 如何在 Swift 中获取数组数据?
- azure-devops - 设置 Azure DevOps ssh 密钥和 git config - 它仍然要求输入密码