gpt4 book ai didi

javascript - jQuery API 架构选择 : why return single value instead of arrays for attr(), val(), ...?

转载 作者:行者123 更新时间:2023-11-30 05:37:27 28 4
gpt4 key购买 nike

我很好奇一些 jQuery API 架构选择背后的原因。

来自文档

属性():

Get the value of an attribute for the first element in the set of matched elements.

验证():

Get the current value of the first element in the set of matched elements.

即使我有很多对象:

$('div').val()

只会返回第一个元素的值。

但 SETTING 的工作方式不同:

val(值):

Set the value of each element in the set of matched elements.

属性(属性名,值):

Set one or more attributes for the set of matched elements.

所以我的问题:

  • 为什么决定像 val() 这样的 getter 操作 应该只返回第一个值而不是值数组?(如果用户想要将它们全部放在一个数组中,则必须使用 map 操作)

  • 为什么不对 setter 操作 做同样的事情,比如 .val(value)?

  • 我可以看到一个用例(使用 $('div').first()),我们希望调用 val() 返回值(我们知道有匹配集中只有一个 dom 元素)而不是长度为 1 的数组。但是为什么不用“单个 dom 元素查询对象”的概念来处理它(仅在调用 first() 或 eq( ))?

最佳答案

注意:我没有参与 jquery 开发,所以这些想法可能完全脱离实际的设计决策。

无论如何,恕我直言,您的建议似乎没有任何优势:

  1. 要处理从 jquery 集合的元素中收集的数据数组,用户无论如何都必须迭代这个数组 - 这可以首先使用 jquery 的 each 方法来完成它具有立即访问带有属性的元素的额外好处:

    $("my_spiffy_selector").each( 函数 ( idx, e ) {
    $(e).attr("blarf").whatever();
    });

  2. Otoh 如果 getter 返回类型是多态的或者如果有不同的 getter,事情就会变得复杂(至少 jquery 代码库)。

  3. 可以说最常见的用例至少需要一个额外的 .first() 调用。

关于javascript - jQuery API 架构选择 : why return single value instead of arrays for attr(), val(), ...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22825085/

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