Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在document.getElementsByTagName上使用索引值_Javascript_Html_Dom_Ecmascript 6 - Fatal编程技术网

Javascript 在document.getElementsByTagName上使用索引值

Javascript 在document.getElementsByTagName上使用索引值,javascript,html,dom,ecmascript-6,Javascript,Html,Dom,Ecmascript 6,为什么常量声明的分号前的[0]起作用 const myHeading=document.getElementsByTagNameh1[0]; const myButton=document.getElementByIdmyButton; const myTextInput=document.getElementByIdmyTextInput; const myP=document.getElementByIdmyP; myButton.AddEventListener单击,=>{ myHeadi

为什么常量声明的分号前的[0]起作用

const myHeading=document.getElementsByTagNameh1[0]; const myButton=document.getElementByIdmyButton; const myTextInput=document.getElementByIdmyTextInput; const myP=document.getElementByIdmyP; myButton.AddEventListener单击,=>{ myHeading.style.color=myTextInput.value; };
它返回一个类似于数组的值HTMLCollection,所以要访问第一个值,可以使用数组表示法[0]。如果不想这样做,请改用querySelector:

将[0]放在对getElementsByTagName的调用之后的原因是,对于返回值的函数,可以将其视为用返回值替换调用-因此,它在调用之后获取第一个元素。如果您愿意,可以这样看:

const headings = document.getElementsByTagName("h1");
const myHeading = headings[0];

它返回一个节点集合。我们需要通过它的索引来访问它

为什么[0]在常量声明的分号之前 工作

记录document.getElementsByTagNameh1的值。你可能会看到这样的情况

{
  "0": <h1> Here is a Header</h1>,
  "length": 1,
  "item": function item() { [native code] },
  "namedItem": function namedItem() { [native code] }
}
这是一个标题
单击该函数返回类似数组的值。为什么您认为它不应该返回?document.getElementByTagName为您提供了类似数组的对象,您可以访问索引我们在这里帮助您使代码正常工作,而不是为代码解释代码。是的,我知道,但为什么它放在document.GetElementsByTagname1后面@Pointy@CodeManiac因为它就在document.getElementsByTagname1之后,这是一个奇怪的地方。我知道吗数组表示法是正确的,但为什么它必须紧跟在document.getElementsByTagNameh1之后呢。我觉得这是个奇怪的地方in@HeavensGate666什么地方不那么奇怪?函数调用的返回值是一个类似数组的对象,因此将数组索引放在函数调用之后是有意义的。
{
  "0": <h1> Here is a Header</h1>,
  "length": 1,
  "item": function item() { [native code] },
  "namedItem": function namedItem() { [native code] }
}