gpt4 book ai didi

javascript - 为什么 $ ('el' )[0].className 有效,但 $ ('el' ).className 无效?

转载 作者:行者123 更新时间:2023-12-01 01:57:34 26 4
gpt4 key购买 nike

我注意到 className 属性在没有索引的 jQuery 中不起作用,这是为什么?

此外,还有其他常见的 JS 属性/方法在 jQuery 中无法按预期工作吗?

HTML:

<div class="par">test</div>

JQuery:

$(function () {

var el = $('.par');

el.className += ' new class'; // doesn't work
el[0].className += ' new class'; // works
});

最佳答案

var el = $('.par'); 返回 jQuery objectclassNameElement 的属性(property)而不是 jQuery object .

jQuery 对象具有类似数组的定义,因此 el[0] 返回底层 Element它具有 className 属性。

据我所知,jQuery 不喜欢开发人员直接更新其属性。它只是公开了各种实用功能以方便开发。

引用David Thomas的好评论下面,

jQuery methods can only be used on jQuery objects; native DOM properties/methods can only be used on native DOM nodes

注意: var el = $('.par'); 返回 Element 的集合,el[0] 返回第一个该列表中的元素。

您可以使用.addClass 向元素添加类。

到第一个元素,

el.eq(0).addClass('new_class');

对于所有元素,

el.addClass('new_class');

更多阅读:

  1. https://developer.mozilla.org/en-US/docs/Web/API/element
  2. https://developer.mozilla.org/en-US/docs/DOM/element.className

关于javascript - 为什么 $ ('el' )[0].className 有效,但 $ ('el' ).className 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16595121/

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