如何通过 JQuery 选择其中没有 html 的 <select> 元素

Posted

技术标签:

【中文标题】如何通过 JQuery 选择其中没有 html 的 <select> 元素【英文标题】:How to select <select> elements with no html in them through JQuery 【发布时间】:2017-01-18 14:04:29 【问题描述】:

我有以下 html 选择元素

    <select  id="options1" title="prd_name" name="options">
       <option value="optiona">Option A</option>
       <option value="optionb">Option B</option>
       <option value="optionc">Option C</option>
    </select>
    <select  id="options2" title="prd_name" name="options"> </select>
    <select  id="options3" title="prd_name" name="options"> </select>
    <select  id="options4" title="prd_name" name="options"> </select>

只有第一个 id="options1" 的选择元素中有选项标签,其余的选择元素是空的。我想选择那些空的选择元素,这样我就可以将选项填充到它们中,而无需触摸已经有选项的第一个选择元素。我怎样才能做到这一点,尤其是通过 Jquery?

【问题讨论】:

【参考方案1】:

您可以使用选择器select:empty;或者你可以使用select:not(:has(option))

console.log($("select:empty"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<select id="options1" title="prd_name" name="options">
  <option value="optiona">Option A</option>
  <option value="optionb">Option B</option>
  <option value="optionc">Option C</option>
</select>
<select id="options2" title="prd_name" name="options"></select>
<select id="options3" title="prd_name" name="options"></select>
<select id="options4" title="prd_name" name="options"></select>

【讨论】:

感谢@guest271314 这个解决方案很完美,可以按我的需要工作。两种形式的代码都有效。【参考方案2】:

试试这个

var $select = $("select").filter(function () 
         return !$(this).find("option").length;
       );
console.log($select);

$select 将为您提供除 with 选项元素之外的所有选择框 然后你可以遍历 $select 并对其执行任何任务

【讨论】:

带有“options1”的选择元素已被选项标签动态填充,它可能是任何选择元素,甚至可能是多个选择元素填充有选项标签。我只想选择那些尚未填充选项标签的选择元素。

以上是关于如何通过 JQuery 选择其中没有 html 的 <select> 元素的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 AJAX 调用使用 jQuery 渲染 HTML

如何通过“选择”插件使用 jQuery 验证?

jQuery 如何选择带有名称和属性的 HTML 输入?

如何通过我的自定义值在 HTML 中设置 SELECT OPTION? [复制]

检查是不是使用 jQuery 选择了选项,如果没有选择默认值

通过php填充多个选择框jquery mobile