我有一个带有一些选项的选择:
<select id="select">
<option>1</option>
<option disabled="true">2</option>
<option>3</option>
</select>
我正在使用 jQuery 选择插件,问题是禁用的选项已从 View 中删除。但我需要将其显示为不可点击的禁用元素。
jquery 选择的插件有机会吗?
-- 该示例将转换为:
<ul class="chzn-results">
<li id="location_select_chzn_o_0" class="active-result result-selected">1</li>
<li id="location_select_chzn_o_2" class="active-result">3</li>
</ul>
所以第二个元素并没有变得不可见,它只是不存在。
最佳答案
nicholmikey 的方法是正确的,但这里是您需要在 selected.jquery.js 中替换的代码,它只是几行简单的代码(下面注释)。希望这会有所帮助。
AbstractChosen.prototype.result_add_option = function(option) {
var classes, style;
option.dom_id = this.container_id + "_o_" + option.array_index;
classes = option.selected && this.is_multiple ? [] : ["active-result"];
if (option.selected) {
classes.push("result-selected");
}
if (option.group_array_index != null) {
classes.push("group-option");
}
// THIS IS NEW ---------------
if (option.disabled) {
classes.push("disabled");
}
// ---------------------------
if (option.classes !== "") {
classes.push(option.classes);
}
style = option.style.cssText !== "" ? " style=\"" + option.style + "\"" : "";
return '<li id="' + option.dom_id + '" class="' + classes.join(' ') + '"' + style + '>' + option.html + '</li>';
};
还有这个
Chosen.prototype.result_select = function(evt) {
var high, high_id, item, position;
if (this.result_highlight) {
high = this.result_highlight;
high_id = high.attr("id");
this.result_clear_highlight();
if (this.is_multiple) {
this.result_deactivate(high);
} else {
this.search_results.find(".result-selected").removeClass("result-selected");
this.result_single_selected = high;
this.selected_item.removeClass("chzn-default");
}
high.addClass("result-selected");
position = high_id.substr(high_id.lastIndexOf("_") + 1);
item = this.results_data[position];
// THIS IS NEW ---------------
if(this.form_field.options[item.options_index].disabled){
return false;
}
// ---------------------------
item.selected = true;
this.form_field.options[item.options_index].selected = true;
if (this.is_multiple) {
this.choice_build(item);
} else {
this.selected_item.find("span").first().text(item.text);
if (this.allow_single_deselect) this.single_deselect_control_build();
}
if (!(evt.metaKey && this.is_multiple)) this.results_hide();
this.search_field.val("");
if (this.is_multiple || this.form_field_jq.val() !== this.current_value) {
this.form_field_jq.trigger("change", {
'selected': this.form_field.options[item.options_index].value
});
}
this.current_value = this.form_field_jq.val();
return this.search_field_scale();
}
};
最后为了让它们变灰,我添加了这个 css...
.chzn-results .disabled{color:#CCC;}
关于jquery 在禁用选项上选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11074530/