Rad*_*dha -1 html javascript jquery
为什么$('.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>
Run Code Online (Sandbox Code Playgroud)
如果我使用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> ]
Run Code Online (Sandbox Code Playgroud)
但是$('.currentMonth'),我只能看到一个元素.
如何使用所有元素$?
该$('.currentMonth')返回所有匹配的元素的jQuery对象.它以jQuery方式包装,但它也返回所有元素.您可以使用以下方法获取元素:
$('.currentMonth').each(function () {
this; // Here this refers to each of the matched element.
});
Run Code Online (Sandbox Code Playgroud)
而document.getElementsByClassname('currentMonth')返回DOM对象列表.
例如,如果我正在执行这样的脚本:
$('.currentMonth').html("Hello!");
Run Code Online (Sandbox Code Playgroud)
所有<td>s都将被更改.
| 归档时间: |
|
| 查看次数: |
654 次 |
| 最近记录: |