未捕获的TypeError: Cannot read property 'style'null - JS

Uncaught TypeError: Cannot read property 'style' of null - JS error

本文关键字:style null JS property read TypeError Cannot      更新时间:2023-09-26

我得到一个javascript错误从我的控制台读取:

Uncaught TypeError: Cannot read property 'style' of null

有谁知道怎么回事吗?

代码(JS):

<script>
    function select()
    {
        document.getElementById('#iframetest').style.display='block';
    }
</script>
代码(HTML):

<iframe src="localhost/createaclass" id="iframetest"></iframe>
<div class="b" onclick="select()">

不要在id (#):

document.getElementById('iframetest')

根据你的评论,你可以这样做:

function select()
{
   document.getElementById('iframetest').style.display = 'block' ? 'none' : 'block';
}

将JS移到HTML下面。

<iframe src="localhost/createaclass" id="iframetest"></iframe>
<div class="b" onclick="select()">
<script>
  function select()
  {
    document.getElementById('#iframetest').style.display='block';
  }
</script>

也许回答太晚了。但你的选择器返回null因为在

这一行
document.getElementById('#iframetest').style.display='block';

你需要把它改成:

document.getElementById('iframetest').style.display='block';

当你指定getElementById时,你的JS将直接转到id为'iframetest'的元素。不需要'#'

如果您正在使用jquery,请尝试此操作。这是工作。

$('.b').click(function(){
$('#iframetest').hide();
});

<iframe src="localhost/createaclass" id="iframetest"></iframe>
<div class="b">selectDiv</div>

参见jsfiddle link http://jsfiddle.net/17duuxcm/5/