gpt4 book ai didi

javascript - id 和 class 对象的长度之间的差异

转载 作者:太空宇宙 更新时间:2023-11-04 14:39:24 24 4
gpt4 key购买 nike

这个 J fiddle 使用 getElementsByClassName

http://jsfiddle.net/YZTpn/

这个 j fiddle 使用 getElementByID

http://jsfiddle.net/9Fa89/

<script>

当我打印出 var "x"的长度时......类和 id 版本的长度不同。 id 版本实际上吐出正确的值,即 4... 而不是 1.... 哪个类吐出。

最佳答案

document.getElementsByClassName

Returns a set of elements which have all the given class names. Whencalled on the document object, the complete document is searched,including the root node. You may also call getElementsByClassName onany element; it will return only elements which are descendants of thespecified root element with the given class names.

Read More..

document.getElementById

Returns a reference to the element by its ID.

Read More

元素.length

length returns the number of items in a NodeList.

Read More

现在在你的 jsfiddles 中..

document.getElementsByClassName("mySelect" ).length是 1.. 为什么?document.getElementsByClassName .. 返回一组元素.. 即一个数组.. 因为只有一个元素的类名为“mySelect”,所以数组的长度将为 1


document.getElementById("mySelect" ).length是 4. 为什么?document.getElementById 返回对元素的引用,因为元素的节点列表中有四个元素..(在您的情况下为 4 <option> s)所以 Element.length 将返回 4..

关于javascript - id 和 class 对象的长度之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19418909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com