【问题标题】:why is it saying I cannot set property fontSize because something is undefined?为什么说我不能设置属性 fontSize 因为某些东西是未定义的?
【发布时间】:2019-11-27 08:17:56
【问题描述】:

我最近参加了为期 5 天的训练营,并在开始完整课程之前尝试自学更多。我正在尝试使用与我在训练营中使用的相同的“鼠标悬停”功能来增加 fontSize,但它说它无法设置未定义的属性 fontSize。我相信我设置了我想要更改的 Id 并指定了我想要更改多少...

老实说,我对此很陌生,只是想克服我的第一个 Javascript 障碍。

function thingHover() {
  document.getElementById('Thing').firstChild.style.fontSize = '300%';
}

function thingNormal() {
  document.getElementById('Thing').firstChild.style.fontSize = '100%';
}
<p id='Thing' onmouseover="thingHover()" onmouseout="thingNormal"> Dunno what I'm gonna do to this text yet, maybe add some JS? </p>

在训练营中,我们将此应用于图标而不是文本。该图标似乎悬停在其原始位置上方略大。我不想只是因为我的文本代码不起作用而复制粘贴图标代码。

【问题讨论】:

  • getElementById 返回单个元素并且p 标签没有任何子元素,因此firstChild 返回undefined
  • 你对比过图标码和你的文字码的区别吗?
  • 每当你遇到像cannot set property B because A is undefined 这样的错误时,你的代码就会在某处出现A.B,而A 是未定义的。在这种情况下,您使用.firstChild 来获取文本节点,并使用.style 来获取样式,但这会产生undefined,因为文本节点没有样式属性。
  • 另外,如果你参加了一个教授使用内联事件侦听器属性的编码训练营和firstElementChild.firstElementChild,你可能应该要求退款。
  • 还应该注意#Thing:hover { font-size: 300% }做同样的事情。

标签: javascript undefined typeerror


【解决方案1】:

这里是下面代码中的拼写错误,调用时添加函数括号

function thingHover() {
           document.getElementById('Thing').style.fontSize='300%'; //remove firstChild
         }
         function thingNormal() {
           document.getElementById('Thing').style.fontSize='100%'; //remove firstChild
         }
           </script>
&lt;p id='Thing' onmouseover="thingHover()" onmouseout="thingNormal()"&gt; Dunno what I'm gonna do to this text yet, maybe add some JS? &lt;/p&gt; &lt;!--add  space between two attributes and add () on onmouseout--&gt;

【讨论】:

  • 哇你们真快!太感谢了!原来它是firstElementChild.firstElementChild。但我现在完全明白它是如何工作的。
  • 如果有帮助,请接受并投票@Matt.Mutt
【解决方案2】:

您没有任何子元素,因此没有第一个子元素:

我做了一些小的修改,这是一个有效的 sn-p。

  function thingHover() {
   var thing = document.getElementById('Thing');
   thing.firstElementChild.style.fontSize = '300%';
  }
  function thingNormal() {
  var thing = document.getElementById('Thing');
    thing.firstElementChild.style.fontSize = '100%';
  }
<script>

</script>
<div id='Thing'onmouseover="thingHover()" onmouseout="thingNormal()">
<p style='fontSize:100%;'>Dunno what I'm gonna do to this text yet, maybe add some JS?</p>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 2016-05-01
    • 1970-01-01
    • 2022-06-18
    • 2013-09-01
    • 1970-01-01
    • 2013-03-25
    相关资源
    最近更新 更多