Javascript:无法使用getElementById获取元素 [英] Javascript: Can't get element using getElementById

查看:73
本文介绍了Javascript:无法使用getElementById获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定。我需要新鲜的眼睛,因为我仍然在这个问题上一小时!

Ok. I need fresh eyes because I'm still on this s***d problem for one hour!

这是我的简单HTML代码(testssio.html),包括javascript脚本:

Here is my simple HTML code (testssio.html) that include javascript script:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        var ssio = document.getElementById('ssio');
        ssio.html = "it finally works!";
    </script>
</head>
<body>
    <div id="ssio"></div>
</body>
</html>

但它不起作用!使用调试器,我得到:

But it doesn't work! Using the debugger, I get:

Uncaught TypeError: Cannot set property 'html' of null          /testssio/:6

有人得到它吗?我知道这不是寻找调试帮助的正确位置,但如果我没有得到它,我会发疯的!那么,请帮忙吗?

Does anyone get it? I know it's not the correct place to look for debugging help, but I'll be crazy if I don't get it! So please, any help?

提前Tahnks。

推荐答案

这样做的原因是头部中的脚本在呈现页面之前加载。这意味着您的内容尚未呈现,因此不属于文档

The reason for this is that scripts in the head load before the page is rendered. This means your content is not yet rendered and therefore not a part of document.

如果您想看到此内容工作,尝试将您的脚本移动到元素渲染下方,如下所示:

If you want to see this work, try moving your script below the element renders, like this:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ssio"></div>
<script type="text/javascript">
    var ssio = document.getElementById('ssio');
    ssio.innerHTML = "it finally works!";
</script>
</body>
</html>

更为标准化的方法是使用事件。许多人使用 jQuery ,但可以使用普通的js完成。这将意味着更改您的脚本:

A more standardized way of doing this is with events. Many people use jQuery but it can be done with plain js. This would mean changing your script like this:

<script type="text/javascript">
  function WinLoad() {
    var ssio = document.getElementById('ssio');
    ssio.innerHTML = "It finally works!";
  }
  window.onload = WinLoad;
</script>

这样你仍然可以把它留在< head>

This way you can still leave it in the <head>.

此外,使用 .html 来自 jQuery 。它通常用作 .html(内容)。如果你想使用普通的javascript版本,请使用 .innerHTML = content

Also, using .html is from jQuery. It is generally used as .html(content). If you want to use the plain javascript version use .innerHTML = content.

我提到jQuery这么多,因为它是一个高度使用的API。这句话来自他们的网站:

I mention jQuery so much because it is a highly used API. This quote is from their site:


jQuery是一个快速简洁的JavaScript库,简化了HTML文档遍历,事件处理,动画和Ajax快速Web开发的交互。 jQuery旨在改变您编写JavaScript的方式。

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

这篇关于Javascript:无法使用getElementById获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆