我注意到className没有索引的jQuery内部属性不起作用,为什么呢?
此外,还有其他常见的JS属性/方法在jQuery中无法正常工作吗?
HTML:
<div class="par">test</div>
Run Code Online (Sandbox Code Playgroud)
JQuery的:
$(function () {
var el = $('.par');
el.className += ' new class'; // doesn't work
el[0].className += ' new class'; // works
});
Run Code Online (Sandbox Code Playgroud)
Sel*_*gam 10
var el = $('.par');返回一个jQuery对象.className是Element上的属性而不是jQuery对象.
jQuery对象有一个类似于定义的数组,因此el[0]返回具有className属性的底层Element.
据我所知,jQuery不喜欢开发人员直接更新其属性.它简单地公开了各种实用功能,以便于开发.
引用下面David Thomas的好评,
jQuery方法只能用于jQuery对象; 本机DOM属性/方法只能在本机DOM节点上使用
注意: var el = $('.par');返回Element的集合并el[0]返回该列表中的第一个元素.
您可以使用.addClass向元素添加类.
到第一个元素,
el.eq(0).addClass('new_class');
Run Code Online (Sandbox Code Playgroud)
对于所有元素,
el.addClass('new_class');
Run Code Online (Sandbox Code Playgroud)
更多阅读: