【问题标题】:Using jQuery, how do I get a specific dropdown element (<select></select>) based on the value of the dropdown?使用 jQuery,如何根据下拉列表的值获取特定的下拉元素 (<select></select>)?
【发布时间】:2022-01-20 08:09:37
【问题描述】:

我有一类下拉菜单——.selMapField——我想选择具有特定值的下拉菜单。例如:

const myattr=$(`.selMapField[value="MYSKU"]`).attr(`x`);

【问题讨论】:

    标签: javascript html jquery jquery-selectors dropdown


    【解决方案1】:

    使用jQuery的.filter()按值查找元素

    const myattr = $(".selMapField").filter((_, { value }) =>
      value === "MYSKU").attr("x")
      
    console.log(myattr)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
    <select class="selMapField" x="A"><option selected>FOO</option></select>
    <select class="selMapField" x="B"><option selected>MYSKU</option></select>
    <select class="selMapField" x="C"><option selected>BAR</option></select>

    一如既往,you might not need jQuery

    const myattr = Array.from(
      document.querySelectorAll(".selMapField")
    ).find(({ value }) => value === "MYSKU")?.getAttribute("x")
      
    console.log(myattr)
    <select class="selMapField" x="A"><option selected>FOO</option></select>
    <select class="selMapField" x="B"><option selected>MYSKU</option></select>
    <select class="selMapField" x="C"><option selected>BAR</option></select>

    【讨论】:

    • 在javascript例子中,“?”的作用是什么?在 "?.getAttribute("x")" 中? ESLint 9 将其标记为问题,但效果很好。
    • 哦...这是可选的链接...多么酷。
    • 没错。我很好奇,什么是 eslint 警告?
    • 需要一个标识符,但看到的是 '.'。 (E030)jshint(E030)
    • 我认为你的 linter 已经过时了~github.com/jshint/jshint/issues/3448
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2016-06-03
    • 2016-07-05
    • 2011-12-15
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多