如何在选择框中的选项前面添加附加文本

jmc*_*mas 2 html jquery

我有一个为客户创建选择框的项目。但他要求的是我不熟悉的东西。基本上,对于选择框中的每个选项,他都想向其中添加附加文本。例如,如果选择此选项:<option value="all">all</option>它将显示为“类别:全部”。我可以更改选择的第一个选项,但是当从下拉列表中选择每个选项时,我需要能够更改每个选项。我相信我已经接近解决方案,只是缺少一些东西。最有可能的是一个改变函数。任何建议将不胜感激jquery

$(function () {
    var selected = $('#selectBox');
    var optionName = $(selected).find("option:selected").text();
    $(selected).find("option:selected").html('<span>category:</span> '+optionName+'');
    console.log(selected);
});
Run Code Online (Sandbox Code Playgroud)

html

 <select id="selectBox" name="selectBox">
                         <option value="all">all</option>
                         <option value="milk">milk</option>
                         <option value="frozen">frozen</option>
                         <option value="cream">cream</option>
                         <option value="sour-cream">sour cream</option>
                         <option value="cottage-cheese">cottage cheese</option>
                         <option value="eggnog">eggnog</option>
                         <option value="calorie-counter">calorie countdown</option>
                         <option value="juices-drinks">juices & drinks</option>
                         <option value="simply-smart">simply smart</option>
                         <option value="our-farmers">our farmers</option>
                     </select>
Run Code Online (Sandbox Code Playgroud)

Dav*_*mas 5

我建议:

// select the select elements (amend to your use-case)
$('select')
// binding an anonymous function as an event handler to the 'change' event:
.on('change', function(){
    // this is the 'select' element
    $(this)
    // find the 'option' elements inside that select:
    .find('option')
    // iterating over each element within the 'text()' method:
    .text(function(i,t){
        // i: is the index of the current element,
        // t: is the current text (before manipulation)
        // if the current option is 'selected' we prepend the text with 'Category: '
        // if not, we remove 'Category: ' (if it's there)
        return this.selected ? 'Category: ' + t : t.replace('Category: ', '');
    });
// trigger the change event, causing the handler to fire (so 'Category: ' is
// prepended to the default-shown 'option' text on page-load:
}).change();
Run Code Online (Sandbox Code Playgroud)

JS 小提琴演示

参考: