You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web开发新手遇JavaScript错误求助:document未定义及JSLint问题

Hey there! Let's work through each of these issues you're hitting with your JavaScript code—totally normal stuff for new devs, so don't stress!

1. Fixing the "document is not defined" Error

This error pops up because your code is running in an environment that doesn't have access to the browser's document object (like Node.js, which is built for server-side work, not interacting with browser DOM elements).

To fix it, you need to make sure your script runs inside a browser, embedded in an HTML file. The best practice is to put your <script> tag at the end of the <body> section—this way, the entire DOM (including your <img> element) loads before your JS tries to access it. Here's how that structure looks:

<!DOCTYPE html>
<html>
<body>
  <img src="images/old-big-garage.png" alt="Garage">
  <!-- Place your script at the end of the body to ensure DOM is ready -->
  <script>
    // Your corrected JS code goes here
  </script>
</body>
</html>
2. Fixing JSLint Warnings

JSLint is pretty strict about code style and best practices—let's tackle each warning one by one:

Missing 'use strict' statement

Adding 'use strict'; at the top of your script (or inside your function) enables strict mode, which helps catch common bugs and enforces cleaner, more intentional code. It's a fantastic habit to build early on!

Expected ... on line 6

This is almost certainly a formatting issue JSLint is flagging. It likely wants consistent spacing around operators and proper line breaks for readability. For example, ensuring spaces around the === comparison operator, and placing the else block on its own line instead of cramming it with the closing brace of the if block.

Full Corrected Code

Here's your code with all fixes applied, plus improved formatting for readability:

'use strict';

var myImage = document.querySelector('img');
myImage.onclick = function () {
  var mySrc = myImage.getAttribute('src');
  if (mySrc === 'images/old-big-garage.png') {
    myImage.setAttribute('src', 'images/name1.png');
  } else {
    myImage.setAttribute('src', 'images/old-big-garage.png');
  }
};

A quick sanity check: If you still see the document is not defined error after adding this to an HTML file, double-check that you're opening the HTML file directly in a browser (not trying to run it through a Node.js script). That's the most common misstep here!

内容的提问来源于stack exchange,提问作者Noah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:31:18