如何在选择框中的选项前添加其他文本

时间:2014-05-21 15:39:12

标签: jquery html

我有一个项目为客户创建选择框。但他要求的是我不熟悉的东西。基本上,对于选择框中的每个选项,他都希望向其添加其他文本。例如,如果选择此选项:<option value="all">all</option>它会像这样&#34; 类别:全部&#34;。我能够更改所选的第一个选项,但是当从下拉列表中选择时,我需要能够更改每个选项。我相信我接近解决方案,只是遗漏了一些东西。最有可能是改变功能。任何建议,将不胜感激 jquery的

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

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>

1 个答案:

答案 0 :(得分:4)

我建议:

// 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();

JS Fiddle demo

参考文献: