gpt4 book ai didi

javascript - 为什么 $ ('.classname' ) & document.getElementsByClassName ('classname' ) 返回不同的东西?

转载 作者:行者123 更新时间:2023-11-28 11:32:59 26 4
gpt4 key购买 nike

为什么 $('.classname') 在 javascript 等效 document.getElementsByClassname('classname') 返回一组元素时只返回一个元素?如果这不是彼此等价的话,那什么才是呢?如何使用 jQuery 获取所有具有相同类名的元素?除了 $('.classname') 之外还有其他方法吗?例如,

<tr>
<td class="currentMonth">1</td>
<td class="currentMonth">2</td>
<td class="currentMonth">3</td>
<td class="currentMonth">4</td>
<td class="currentMonth">5</td>

如果我使用 document.getElementsByClassName('currentMonth'),那么我将获得上面提到的所有元素的数组。

[ <td class="currentMonth">1</td>,    <td class="currentMonth">2</td>, <td class="currentMonth">3</td>,    <td class="currentMonth">4</td>,    <td class="currentMonth">5</td> ]

但是使用 $('.currentMonth'),我只能看到一个元素。

如何使用 $ 获取所有元素?

最佳答案

$('.currentMonth')返回所有匹配元素的 jQuery 对象。它以 jQuery 方式包装,但它也返回所有元素。您可以使用以下方式获取元素:

$('.currentMonth').each(function () {
this; // Here this refers to each of the matched element.
});

document.getElementsByClassname('currentMonth')返回 DOM 对象的列表。

例如,如果我执行这样的脚本:

$('.currentMonth').html("Hello!");

所有<td> s 将被更改。

关于javascript - 为什么 $ ('.classname' ) & document.getElementsByClassName ('classname' ) 返回不同的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34331838/

26 4 0