document.getElementById()不起作用-可能是因为页面尚未加载

document.getElementById() not working - maybe because page is not loaded yet?

本文关键字:是因为 加载 getElementById 不起作用 document      更新时间:2023-09-26

可能重复:
为什么jQuery或诸如"getElementByID"之类的DOM方法找不到元素?

在HTML标记之前,我运行了一些php代码。在此期间,我需要包括一些javascript行,如

..php code...
..javascript code...
..php code..
<html>
<head>
</head>
<body>
<input type="file" name="file" id="file">
</body>
</html>

在javascript代码中,我想隐藏file元素。

这没有任何作用:

..php code
?>
<SCRIPT LANGUAGE="JavaScript">
 document.getElementById('file').style.display = 'none';
</script>
<?php

php代码

如果我在那里放了一个警报,它就会被显示

如果我将该行放入<head></head>块中的一个函数中,并从例如按钮的onClick事件中调用它,则文件元素将被隐藏,因此该行很好。也许document.getLementByID在html标记之外无效?或者问题是页面还没有加载,所以没有具有该id的元素?如果是这种情况,我该怎么办?

解决方案

我在php代码中添加了一个变量$int=1;(和$int=0;在其他地方,但仍在加载页面之前(。然后在<head></head>块中:

window.onload = selectChoose;
function selectChoose() 
{
    if (<?php echo $int ?> == 0) {
        showChoose();
    }
    else {
        hideChoose();
    }
}
function showChoose() 
{
    document.getElementById('file').style.display = 'inline';
}
function hideChoose() 
{
    document.getElementById('file').style.display = 'none';
}

正如您所说,它只是还没有加载。

影响特定元素的JavaScript必须被延迟(window.onload,在事件处理程序上,等等(,或者放在它试图修改的元素之后。

Window onload将为您解决此问题。像这样:

window.onload = function(){
     document.getElementById('file').style.display = 'none';
    }

这意味着一旦整个站点加载then,它将执行style.display命令:(