Javascript元素为null [英] Javascript element is null

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

问题描述

我是javascrit的初学者,我试图获得表格结果全球

I am a begginer at javascrit, and im trying to get a form result globaly

单选按钮

<input type='radio' name='supporter' id='supporter' value='yes'>

和其他页面上的javascript

and the javascript on the nother page

<script type="text/javascript">
function show(){
    var supporter = document.getElementById('supporter');
    if (supporter.value == "yes") {
        alert("it works")
    }
}

show();
</script>

我一直收到错误,这个:支持者是空的

and i keep getting an error, this: supporter is null

可以请有人告诉我我缺少什么吗?

can please someone tell me what im missing?

推荐答案

这将取决于何时脚本被执行。 Javascript由浏览器在遇到时执行,这意味着如果您的代码片段存在于之前的 HTML元素中,那么在该时间点,HTML元素尚不存在。

It will depend on when the script is executed. Javascript is executed by the browser as it is encountered, which means that if your snippet of code exists in the page before the HTML element, then at that point in time, the HTML element does not yet exist.

一种解决方案是将Javascript放在页面的最后,或将该代码移到 document.onload b。处理器。

One solution would be to put the Javascript at the very end of the page, or move that code into the document.onload handler.

document.onload = function () {
    show();
};

这篇关于Javascript元素为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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