显示每个选择选项jquery的描述

时间:2011-01-17 00:16:31

标签: jquery html

我遇到了一个问题,并希望能够围绕它设计一个富有创意且轻量级的方法。每次用户从选择列表中选择选项时,我都需要显示描述性文本。我会使用类似的东西:

$('#description').html($(this).attr('title') );

但是标题标签被一个名为msDropdown(一个皮肤插件)的插件使用,并且由于它而似乎无法正常运行。

感谢任何帮助。

2 个答案:

答案 0 :(得分:7)

如果我是你,我会避免使用title属性。这不是它的用途。使用自定义data-属性 - 它们具有语法意义,是HTML5下的有效HTML,并且在所有浏览器中都能很好地运行,jQuery将它们集成到data()功能中。

例如:

HTML:

<select id="mySelect">
    <option value="1" data-description="Item 1">Item 1</option>
    <option value="2" data-description="Item 2">Item 2</option>
    <option value="3" data-description="Item 3">Item 3</option>
</select>
<span id="description"></span>

jQuery的:

$('#mySelect').change(function(){
    var $selected = $(this).find(':selected');

    $('#description').html($selected.data('description'));
}).trigger('change'); // run handler immediately

See jsFiddle example

答案 1 :(得分:2)

我采用略有不同的方法,并使用select列表和ol(或任何其他元素)之间的配对:

HTML:

<select id="selectElement" id="selectElement">
    <optgroup label="Select a fruit">
        <option value="apples">Apples</option>
        <option value="oranges">Oranges</option>
    </optgroup>
</select>

<ol id="explanatoryText">
    <li>The first option chooses 'apples.'</li>
    <li>This option chooses 'oranges' instead.</li>
</ol>

的CSS:

ol#explanatoryText li {
    display: none;
}

ol#explanatoryText li.descriptor {
    display: list-item;
}

jQuery的:

$('#selectElement').click(
    function(){
        $(this).change();
    });
$('#selectElement').change(
    function(){
        var index = $(this).find('option:selected').index();
        $('#explanatoryText li.descriptor').removeClass('descriptor');
        $('#explanatoryText li').eq(index).addClass('descriptor');
    });

JS Fiddle demo