简体   繁体   English

jQuery获取选择选项的兄弟姐妹

[英]jquery get select option siblings

I'm trying to get all options other than the selected one and with the different class than the selected one. 我正在尝试获取除所选选项之外的所有选项,并且具有与所选选项不同的类。

Consider the following example: 考虑以下示例:

<select name="country" id="country">

    <option value="1" class="option_vat" selected="selected">United Kingdom</option>
    <option value="2" class="option_no_vat">United States</option>
    <option value="3" class="option_vat">Spain</option>
    <option value="4" class="option_vat">Portugal</option>

</select>

Now when change() event is called I want to get the class of the selected option and classes of other options, which are different to the selected one. 现在,当调用change()事件时,我想获取所选选项的类和其他选项的类,它们与所选选项不同。 In this case the only class that would be added to array would be 'option_no_vat' as Spain and Portugal option have the same class at the selected one (United Kingdom). 在这种情况下,唯一要添加到数组的类将是“ option_no_vat”,因为西班牙和葡萄牙选项在所选的那个(英国)具有相同的类。

Could someone suggest a solution please? 有人可以提出解决方案吗?

http://jsfiddle.net/vKXMP/1/ http://jsfiddle.net/vKXMP/1/

$("select#country").change(function(){
    var $that, cls;
    $that = $(this);
    cls = $that.find("option:selected").attr("class"); //returns the class of the selected elements... only works when there is only one class
    console.log( $that.find("option").not("."+cls) ) //gives you back a jquery object of all the elements with a different class then the one selected
});

next time, at least try something. 下次,至少尝试一下。

Here you go 干得好

Working demo 工作演示

$(function(){
    $("#country").change(function(){
        var classes = [], class;
        var currentClass = $(this).find("option:selected").attr('class');
        $(this).find("option").each(function(){
            class = $(this).attr('class');
            if(class != currentClass){
                if($.inArray(class, classes) == -1){
                    classes.push(class);
                }
            }
        }); 
        alert(classes.join(","));
    }).change();
});

classes array will contain all the unique classes which you need. classes数组将包含您需要的所有唯一类。

Try this: 尝试这个:

var classes;

$('#country').change(function()
{
    classes = [];

    $(this).find('option:not(:selected)')
        .not('.' + $(this).find(':selected').attr('class'))
        .each(function()
        {
            var class = $(this).attr('class');

            if ( $.inArray( class, classes ) == -1 )
                classes.push(class);
        });
});

http://jsfiddle.net/9JEyY/ http://jsfiddle.net/9JEyY/

Note: This'll only work correctly if you have just one class per element. 注意:仅当每个元素只有一个类时,此方法才能正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM