问题
I'm using "Chosen plugin" and not sure how to add an attribute to the option tags of the select list.
I have tried this using jQuery on document ready but no luck.
回答1:
you need to modify the Chosen.Jquery.js to the following to make it work
Using Chosen 1.0 version
Line no 62 add this line of code
this.parsed.push({
array_index: this.parsed.length,
options_index: this.options_index,
value: option.value,
text: option.text,
html: option.innerHTML,
title: option.title, // this is Line 62 add this line
selected: option.selected,
disabled: group_disabled === true ? group_disabled : option.disabled,
group_array_index: group_position,
classes: option.className,
style: option.style.cssText
});
Modify Line No 255
return "<li title=\"" + option.title +"\" class=\"" + (classes.join(' ')) + "\"" + style + " data-option-array-index=\"" + option.array_index + "\">" + option.search_text + "</li>";
回答2:
I have tried this..but no luck
That depends what you tried. Give this function a go, calling it with the select element that you want its chosen counterpart to inherit titles
function cloneTitles(selectBox) {
//make sure it has already been chosen-ised
selectBox = $(selectBox).chosen();
//get all the original options, should be in same order as chosen ones
var origOpts = selectBox.find('option');
//get all the chosen-created 'options'
//NB there may be a better way to grab the chosen created element
var chznOpts = selectBox.next().find('.active-result')
//foreach option
origOpts.each(function(index, origOpt) {
//copy the attribute from the original
$(chznOpts[index]).attr('title', $(origOpt).attr('title'));
});
}
I have tried this on document ready
Your problem may have been that you were doing whatever you tried before chosen.js had converted your select boxes, but this function should mitigate that.
Also, if you need this for multiple select boxes, just use .each()
(E.g. selectArray.each(function(i, select) { cloneTitles(select); })
I assume you're using jQuery and not Prototype (given your last line)
So you could pass in '#id' instead of <DOMObj> if you wanted.
Code could be modified to clone a given attribute, instead of 'title'
, or even an array of given attributes!
回答3:
Using Chosen 1.1 version
html: option.innerHTML, // Search
title: option.title, // Add
.
option_el.innerHTML = option.search_text; // Search
option_el.title = option.title; // Add
来源:https://stackoverflow.com/questions/14569903/how-to-add-title-attribute-to-chosen-option-tags