从 jQuery 中的所有元素中获取属性的值

Jos*_*rns 6 javascript jquery attributes

假设我们有以下 HTML:

<entries>
  <entry id="1" />
  <entry id="2" />
  <entry id="3" />
  <entry id="4" />
</entries>
Run Code Online (Sandbox Code Playgroud)

jQuery 是否具有用于检索特定属性的所有值的内置机制?如果没有,那么检索它们的最有效方法是什么?

例如,类似于: $('entry').attrs('id'),返回所有元素的值列表,返回类似于["1", "2", "3", "4"]?

General Attributes下的 jQuery 文档(attr找到的位置)没有给出任何存在的提示,我在 StackOverflow 或任何其他支持论坛上也没有发现任何询问这个问题的内容。

Dan*_*ger 0

您可以使用扩展 jQueryjQuery.fn.extend()并添加一个自定义方法来迭代所有匹配元素,从所有元素中提取单个或多个属性,并将它们分别推送/合并到返回的数组/对象中。

由于实现是普通 JS,这将比在所有中间步骤中使用 jQuery 对象和函数更快,但可能需要一些调整,具体取决于您需要支持的浏览器:

jQuery.fn.extend({
  attrs: function(attributeName) {
    if (attributeName) {
        return this.toArray().map((el) => el.getAttribute(attributeName));
    }
    
    return this.toArray().reduce((merged, el) => {
      const { attributes } = el;
      const totalAttributes = attributes.length;

      for (let i = 0; i < totalAttributes; ++i) {  
        const attribute = attributes[i].nodeName;

        if (merged[attribute]) {
          merged[attribute].push(el.getAttribute(attribute));
        } else {
          merged[attribute] = [el.getAttribute(attribute)];
        }
      }

      return merged;
    }, {});
  },
});

console.log($('entry').attrs());
console.log($('entry').attrs('id'));
console.log($('entry').attrs('class'));
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {
  max-height: 100% !important;
}
Run Code Online (Sandbox Code Playgroud)
<entries>
  <entry id="1" class="foo" />
  <entry id="2" class="bar" />
  <entry id="3" class="baz" />
  <entry id="4" class="qux" />
</entries>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)