【问题标题】:How to retrieve all jQuery elements with an attribute that starts with a value? [duplicate]如何检索具有以值开头的属性的所有 jQuery 元素? [复制]
【发布时间】:2021-06-21 08:13:43
【问题描述】:
<div data-start-one="one"></div>
<div data-start-one="one"></div>
<div data-start-two="two"></div>
<div data-start-three="three"></div>

如何检索所有具有以data-start 开头的 jQuery 属性的元素?

例如:$("div[data-start-*]")

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    没有什么好的方法可以做到这一点。您必须遍历可能与您想要的匹配的 所有 元素,然后将它们过滤掉。

    const starts = $('div').filter(function() {
      return [...this.attributes].some(
        attrib => attrib.name.startsWith('data-start')
      );
    });
    console.log(starts.length);
    console.log(starts[3]);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div data-start-1="one"></div>
    <div data-start-1="one"></div>
    <div data-start-2="two"></div>
    <div data-start-3="three"></div>
    <div class="somethingElse"></div>

    更好的方法是能够使用其他共同点来选择这些元素,例如类或其他数据属性或容器的后代。

    const starts = $('.container div');
    console.log(starts.length);
    console.log(starts[3]);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="container">
      <div data-start-1="one"></div>
      <div data-start-1="one"></div>
      <div data-start-2="two"></div>
      <div data-start-3="three"></div>
    </div>
    <div class="somethingElse"></div>

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 2015-05-21
      • 2018-07-02
      • 2017-05-26
      • 2015-11-25
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-20
      相关资源
      最近更新 更多