【问题标题】:Why is document not working on JavaScript为什么文档不适用于 JavaScript
【发布时间】:2019-09-27 21:38:47
【问题描述】:

我查看了各种网站,但没有任何帮助。对我来说一切似乎都是正确的,但我无法得到 ​​p>

document.getElementByClassName("first").style.display="none"; 

无论我尝试了多少次,我总是在 JS 上收到相同的错误消息;

错误:'document' 未定义。[no-undef]

尝试定义“文档”部分但没有帮助。也许,我在做外部文件夹之间的连接不正确我试过了,没有任何改变

HTML:

<html>
 <head>
       <script src="JS.js"></script>
 </head>
 <body>
 <div class="first">
    <p>Hello and welcome to my first page<br>
    in this page I will test out new think<br>
    and see what works and what doesn't<br>
    </p>
</div>
<button type="button" onclick="myFunction">Click me</button>
</body>
</html>

JS:

function myFunction(){
    document.getElementsByClassName("first").style.display="none";

该按钮应该从“第一个”清除所有他的样式。我已经更改了许多结果并且代码没有发生任何事情,只是同样的错误一遍又一遍地重复自身。

【问题讨论】:

  • onclick="myFunction()"
  • 如果没有其他方法,请确保在开始之前在 .first 类中定义了 display: block

标签: javascript html css


【解决方案1】:

您收到的错误似乎来自 linter,但与您的代码无法正常工作无关。要解决您的 linter 问题,您可能想看看这个post。 对于运行时产生的错误,您应该查看浏览器控制台(大多数情况下使用 F12 打开)。

关于您的主要问题,有两件事需要解决:

1)
您的内联 onclick 处理程序应该像这样调用:

<button type="button" onclick="myFunction()">Click me</button>

2)
而不是使用 document.getElementsByClassName() - 它返回一个数组 - 我建议您改用 document.querySelector(),因为它只返回找到的第一个元素,并且如果您已经熟悉 css 选择器,那么使用起来会更容易。 有关查询选择器功能的更多信息,请查看this page

所以,在你的代码中应该是这样的:

function myFunction() {
  document.querySelector(".first").style.display="none";
}

【讨论】:

    【解决方案2】:

    document.getElementByClassName() 返回一个元素数组,因此您需要要定位的元素的索引。

    您应该通过myFunction()调用该函数并将[0]添加到getElementsByClassName以获取特定元素。

    function myFunction() {
        document.getElementsByClassName("first")[0].style.display="none";
    }
    <html>
     <head>
           <script src="JS.js"></script>
     </head>
     <body>
     <div class="first">
        <p>Hello and welcome to my first page<br>
        in this page I will test out new think<br>
        and see what works and what doesn't<br>
        </p>
    </div>
    <button type="button" onclick="myFunction()">Click me</button>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2021-02-23
      • 2021-06-07
      • 2013-10-08
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多