将属性禁用设置为不包含特定字符串的选项

时间:2010-05-12 19:47:22

标签: jquery attributes

我知道如果我只能使用optgroup,这会更容易。但我试图避免黑客攻击我的CMS的核心,所以jQuery应该再来救援,希望。

我有时会在层次结构中选择一个选项,并且我希望将属性禁用到包含不以短划线开头的文本的任何选项。 我想编码如下:

将禁用的属性设置为选项文本,选项文本不以短划线(“ - ”)开头。

<select id="options">
<option value="" selected="selected">- Please choose -</option>
<option value="1">Parent1</option>
<option value="2">-child1</option>
<option value="3">-child2</option>
<option value="4">-child3</option>
<option value="5">-child4</option>
<option value="6">Parent2</option>
<option value="7">-child5</option>
<option value="8">-child6</option>
<option value="9">-child7</option>
<option value="10">-child8</option>
</select>

最接近的解决方案是 :contain / start by

$.extend($.expr[':'], {
    startsWith: function(elem,match) {  
        return (elem.textContent || elem.innerText || "").indexOf(match[3]) == 0;
    }  
});

但是我似乎无法做到这一点。

非常感谢任何帮助。非常感谢你。

1 个答案:

答案 0 :(得分:1)

您可以使用.filter(),如下所示:

​$("#options option").filter(function() {
    return $(this).text().indexOf("-") !== 0;
}​).attr('disabled', true);​​

这会滤除所有没有以"-"you can see a demo here开头的文字的元素。

自定义选择器方法就像你的问题一样:

$.extend($.expr[':'], {
    startsWith: function(a, b, match) {
        return $(a).text().indexOf(match[3]) === 0;
    }  
});

$("#options option:not(:startsWith(-))").attr('disabled', true);​

You can see a demo of that method here