简体   繁体   English

根据自定义属性过滤SELECT选项

[英]Filter SELECT options based on custom attribute

I have a select list with options that each contain a custom attribute of "active" which is either equal to "T" or "F". 我有一个选择列表,每个选项包含一个自定义属性“ active”,该属性等于“ T”或“ F”。 I'm trying to set up a javascript or jQuery function that will allow me to filter the options to only show those whose active attribute is equal to "T" or whose active attribute is equal to "F" based on which button they click. 我正在尝试设置一个JavaScript或jQuery函数,该函数将允许我过滤选项以仅显示其活动属性等于“ T”或其活动属性等于“ F”的用户(基于他们单击的按钮)。 Essentially having "Show Active" / "Show Inactive" buttons that will hide/show the appropriate select options. 本质上具有“显示活动” /“显示不活动”按钮,它们将隐藏/显示适当的选择选项。

Does anyone have any samples they could provide to get me started? 是否有人可以提供样品以帮助我入门? Thank you very much in advance! 提前非常感谢您!

function toggleUnitsSelector(active)
{
    $('#unitsSelector option').each(function() {
        if($(this).attr("active")==active){
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}

Using the example provided by David Xu I came up with the function above. 使用David Xu提供的示例,我想到了上面的功能。 It does indeed limit the options to only the ones marked as active="T" when I click my "show active" button, however it shows an empty select box when trying for inactive. 当我单击“显示活动”按钮时,确实确实将选项限制为仅标记为活动=“ T”的选项,但是,当尝试不活动时,它会显示一个空的选择框。 I can see in Google Chromes dev tools that the markup is being changed and when I select "show inactive" the ones that were marked with style="display:none;" 我可以在Google Chrome浏览器开发工具中看到标记已被更改,并且当我选择“显示无效”时,标记为style =“ display:none;”的标记将被更改。 switch to style="display:inline;" 切换到style =“ display:inline;” but they do not show up. 但它们没有出现。 Any ideas? 有任何想法吗? Also, I'm calling this function toggleUnitsSelector('T') or toggleUnitsSelector('F') 另外,我将此函数称为toggleUnitsSelector('T')或toggleUnitsSelector('F')

A fairly easy option is to combine an updated version of this plugin: https://stackoverflow.com/a/9234883/2287470 with a simple event handler: 一个相当简单的选择是将该插件的更新版本: https : //stackoverflow.com/a/9234883/2287470与一个简单的事件处理程序结合在一起:

$.fn.toggleOption = function( show ) {
    return this.each(function(){
        $(this).toggle(show);
        if(show) {
            if($(this).parent('span.toggleOption').length) $(this).unwrap();
        } else {
            $(this).wrap('<span class="toggleOption" style="display: none;" />');
        }
    });
};

var list = $('select option'), buttons = $('button');

list.toggleOption(false);

buttons.on('click', function () {
    var filter = $(this).hasClass('active') ? "[data-active=F]" : "[data-active=T]";
    list.toggleOption(true).filter(filter).toggleOption(false);
});

This hides the options in a cross browser compatible way and still remains quite small in size. 这以跨浏览器兼容的方式隐藏了选项,并且尺寸仍然很小。 Here it is working: http://jsfiddle.net/jTngY/2/ 它在这里工作: http : //jsfiddle.net/jTngY/2/

With jQuery loop over each "option" item within the "select" tag: 使用jQuery循环遍历“选择”标记内的每个“选项”项:

$("#select_list option").each(function(i,o) {
   if (o.attr("active") == "T") {
      console.log(o + " is T");
   }
});

Hope this helps 希望这可以帮助

I do sometimes like this: 我有时会这样:

someSelectInit($("select"));

$("a.someLink").click(function(){
    someSelectFilter($("select"), 'someAttrName','someAttrValue');
    return false;
});

function someSelectInit(objects)
{
    $(objects).each(function(i,e){
        that = $(e);
        options = [];
        that.find('option').each(function(optionIndex, optionElement){
            option = $(optionElement);
            options.push({
                value: option.attr('value'),
                text: option.text(),
                someAttrName: option.attr(someAttrName)
            });
        });
        that.data('options', options);
        that.find("option:not(:disabled)").remove();
    });
}

function someSelectFilter(selectElement, attrName, attrValue)
{
    selectElement = $(selectElement);
    selectElement.find('option:not(:disabled)').remove();
    options = $(selectElement).data('options');
    for(var i in options)
    {
        if(options[i].someAttrName != attrValue)
            continue;

        option = $('<option />').attr('value', options[i].value).text(options[i].text);
        selectElement.append(option);
    }
}

Without using jQuery, and assuming each list item has a class attribute of 'select_list_option' 无需使用jQuery,并假设每个列表项的类属性均为“ select_list_option”

function showItemsForType(type) {
    var elementList = document.getElementsByClassName('.select_list_option'),
        elementArray = Array.prototype.slice.call(elementArray);

    elementArray.forEach(function(el) {
        if (el.getAttribute('active') === type) {
            // display el
        }
    });
}

showItemsForType('T');

Sadly, there is no happy answer for this because IE is the spawn of the Devil . 可悲的是,对此没有满意的答案,因为IE是Devil的产物。 . .

This should be as easy as: 应该很简单:

function toggleUnitsSelector(active) {
    $("#unitsSelector option").hide();
    $("#unitsSelector option[active='" + active + "']").show();
}

And that works great in all of the reasonable browsers, however, IE (in at least most, if not all of their versions) is not a reasonable browser and, therefore, will not allow you to hide select options. 这在所有合理的浏览器中都很好用,但是,IE(至少在大多数情况下,如果不是其所有版本,则不是)不是合理的浏览器,因此,不允许您隐藏选择选项。

So, in order to get them to not display in IE, you have to "get creative", and by "get creative", I mean do things that you should never have to do to support this kind of functionality. 因此,为了使它们不显示在IE中,您必须“获得创造力”,而通过“获得创造力”,我的意思是做一些您不必为支持这种功能而必须做的事情。

One such solution that you could use would be to have two hidden <select> elements that each contained the active="T" and active="F" options separated out and use those to populate the primary selector (which I defaulted to the "active" options), as needed: 您可以使用的一种这样的解决方案是,将两个隐藏的<select>元素分隔开来,每个元素分别包含active="T"active="F"选项,然后使用这些元素填充主选择器(我默认将其设置为“有效”选项),根据需要:

<style>
     .hidden {display: none;}
</style>

<div>
    <select id="unitsSelector">
        <option value="1" active="T">1</option>
        <option value="2" active="T">2</option>
        <option value="4" active="T">4</option>
        <option value="6" active="T">6</option>
        <option value="10" active="T">10</option>
    </select>
    <select id="hiddenSelectorT" class="hidden">
        <option value="1" active="T">1</option>
        <option value="2" active="T">2</option>
        <option value="4" active="T">4</option>
        <option value="6" active="T">6</option>
        <option value="10" active="T">10</option>
    </select>
    <select id="hiddenSelectorF" class="hidden">
        <option value="3" active="F">3</option>
        <option value="5" active="F">5</option>
        <option value="7" active="F">7</option>
        <option value="8" active="F">8</option>
        <option value="9" active="F">9</option>
    </select>

    <input type="button" onclick="javascript: toggleUnitsSelector('T');" value="Show Active" />
    <input type="button" onclick="javascript: toggleUnitsSelector('F');" value="Show Inactive" />
</div>

<script type="text/javascript">
    function toggleUnitsSelector(active) {
        $("#unitsSelector").empty();
        $("#hiddenSelector" + active + " option").each(function() {
            $(this).clone().appendTo($("#unitsSelector"));
        });
    }
</script>

Every time, you click the buttons, it clears out the displayed dropdown and populates it with the options from whichever hidden dropdown contains the options that it needs. 每次单击按钮时,它都会清除显示的下拉菜单,并使用其中包含所需选项的任何隐藏下拉菜单中的选项填充它。 And, it works in all browsers . 并且,它适用于所有浏览器。 . .

There are many other approaches that you could potentially use (store the values in an array and build the options that you want to show, for example), but, due to IE's inability to play well with others, they are all going to involve some sort of removal of the options that you don't want to display. 您可能会使用许多其他方法(例如,将值存储在数组中并构建要显示的选项),但是由于IE无法与其他人很好地玩,它们都将涉及到删除了您不想显示的选项。

Wish it could be as easier . 希望它会更容易。 . .

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

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