简体   繁体   English

为什么我的 var 是 null 并且代码不起作用

[英]Why my var is null and the code doesn't work

I'm starting with the basics in JS and I try to make my first event, change the image if it clicked but it's not working, where's the prob?我从 JS 的基础知识开始,我尝试制作我的第一个事件,如果点击了更改图像但它不起作用,问题在哪里?

let myImage = document.querySelector('img');

myImage.onclick = function() {
    let mySrc = myImage.getAttribute('src');
    if(mySrc === 'images/coding_icon.png') {
      myImage.setAttribute ('src','images/coding2.png');
    } else {
      myImage.setAttribute ('src','images/coding_icon.png');
    }
}

My var myImage return NULL and nothing happen when I click on my image.我的 var myImage 返回 NULL 并且当我单击我的图像时没有任何反应。 It seems that the doc...selector don't select the first occur of img.似乎文档...选择器不是 select 第一次出现的 img。 Sorry if I did something wrong with the post, it's my first time posting here.抱歉,如果我在帖子中做错了什么,这是我第一次在这里发帖。 Thanks谢谢

You are probably using querySelector on img before it really loaded into DOM.您可能在 img 真正加载到 DOM 之前在它上使用 querySelector。

Possible solutions:可能的解决方案:

1) move your script in the body tag after the img tag declaration. 1)在img标签声明之后将您的脚本移动到body标签中。

2) use code on event of other tags, for eg on a button click 2)在其他标签的事件上使用代码,例如在按钮点击上

3) you can put a timeout surrounding script so that it run delayed and DOM can be loaded meanwhile 3)您可以在脚本周围放置一个超时,以便它延迟运行,同时可以加载DOM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM