【问题标题】:how to get text from <option> in <select> with display none set by selectize如何从 <select> 中的 <option> 获取文本,其中 display none 由 selectize 设置
【发布时间】:2014-08-27 07:31:15
【问题描述】:

我将 seletize 0.11.0 用于 bootstrap2。我想从&lt;option&gt; 获取具有特定值的文本。

我试过了:

$("#id_sel option[value='1']").text();

我什么都没有。

html元素&lt;select&gt;的属性显示为none。

好吧,那该怎么做呢?感谢您的考虑。

编辑

样品

<body>
    <select id="id_sel" multiple='multiple'>
        <option selected='selected' value='1'>first</option>
        <option value='2'>second</option>
        <option selected='selected' value='3'>third</option>
    </select>
</body>

js

$("#id_sel").selectize();
alert($("#id_sel option[value='1']").text());

现在我知道了

在选项标签之间选择remove text,并使选择显示为无。是有线的。

所以在运行时选择看起来像:

<select id="id_sel" multiple="multiple" class="selectized" style="display: none;">
    <option selected='selected' value='1'></option>
    <option value='2'></option>
    <option selected='selected' value='3'></option>
</select>

好吧,我仍然不知道如何获取文本。

【问题讨论】:

  • 可以分享html示例吗
  • 哪个html元素有属性显示无(选择或选项)
  • 我把它放在jsfiddle
  • &lt;select&gt; 的属性显示无。 @AnkitAgrawal
  • 你试过selectize.getValue();吗?

标签: jquery html css selectize.js


【解决方案1】:
<script>  

    jQuery(document).ready(function()
    {
        $("#id_sel option").each(function()
        {
            if(!$(this).is(':visible'))
            {
                alert($(this).val());
            }
        });                        
    });

</script>



<select id="id_sel">
    <option>select</option>
    <option style="display: none;">1</option>
    <option>2</option>
</select>

通过此代码,您可以获得隐藏选项字段的值

【讨论】:

  • 这似乎不适用于text()。我需要在 之间获取文本。
【解决方案2】:

嗯,应该有一些 api 来获得它。如果不是,那就太奇怪了。我试过getOption() and getItem()。这不是工作。选择不要在我使用的版本的选项标签中添加文本。它将&lt;select&gt;设为none,并创建一组div来覆盖&lt;select&gt;的位置。在我的版本中,它看起来像:

<div class="selectize-control multi">
    <div class="selectize-input items full has-options has-items">
        <div data-value="1" class="item">first</div>
        <div data-value="2" class="item">second</div>
        <input ....
        ....
    </div>
</div>

目前,我使用 jquery 多选择器来获取文本。

$(".selectize-control .selectize-input div").each(function() {
    if (1 == $(this).data("value")) {
        alert($(this).text());
    }
});

或通过id标识

$("#id_sel").siblings(".selectize-control").find(".selectize-input div").each(function() {
    if (1 == $(this).data("value")) {
        alert($(this).text());
    }
});

希望这对其他人有帮助。最好的答案应该是使用 api 来做到这一点。

【讨论】:

    【解决方案3】:

    你可以使用

    $("#id_sel option").each(function()
    {
        // here you can use $(this).text()
    });
    

    【讨论】:

    • 我想获取选项的文本而不是值。
    • 然后你可以使用 $(this).text()
    【解决方案4】:

    这是你提到的工作代码:

    $("#id_sel option").val("1").text();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-10
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 2014-09-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      相关资源
      最近更新 更多