【问题标题】:jQuery selector for <select>'s <option> box<select> 的 <option> 框的 jQuery 选择器
【发布时间】:2014-05-21 09:21:06
【问题描述】:

鉴于下面的 HTML,我需要一个 jQuery 选择器来选择 &lt;option&gt;with-stamp 类。

<select name="preset_select">
    <option selected="selected" value="original">ORIGINAL</option>
    <option value="large">LARGE</option>
    <option class="with-stamp" value="medium">MEDIUM</option>
</select>

$("select[name=preset_select]").change(function() {
    // console.log( $(this).hasClass("with-stamp") ); // all false
    // console.log( $("select[name=preset_select] option").hasClass("with-stamp") ); // all true
});

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:
    $("select[name='preset_select']").change(function() {
        $(this).children(':selected').hasClass('with-timestamp')
    }
    

    【讨论】:

    • 谢谢你,一开始我以为我没有工作,但我看到你改变了我的班级名称:-)
    • 对不起,我的错。很高兴你明白了:)
    【解决方案2】:

    您只需要检查:selected &lt;option&gt; (因为如果集合中的任何 个元素具有类,则.hasClass() 返回true),如下所示:

    $("select[name=preset_select] option:selected").hasClass("with-stamp")
    

    【讨论】:

    • 我更喜欢 PeeHaa 的,因为它使用 $(this)
    【解决方案3】:
    $("select[name=preset_select] option:selected").hasClass('with-stamp').change(function() { 
    
    }); 
    

    【讨论】:

    • 有一个.class 选择器,但除此之外,change 事件不会在&lt;option&gt; 上触发,它会在&lt;select&gt; 上触发。
    猜你喜欢
    • 2012-12-10
    • 1970-01-01
    • 2019-02-09
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2012-12-29
    相关资源
    最近更新 更多