HTML选择:如何在<select>关闭时更改标签?</select>

时间:2012-01-16 13:38:31

标签: javascript html

考虑一下:

    <select name="month_selection">
        <optgroup label="2012">
            <option value="1">January</option>
        </optgroup>
        <optgroup label="2011">
            <option value="1">January</option>
            <option value="2">February</option>

上面的HTML在打开时看起来像#1,在关闭时看起来是#2 如何让封闭版看起来像#3?

目的是显示所选年份而不在打开选项中重复它(因此它看起来更干净)。

enter image description here

3 个答案:

答案 0 :(得分:1)

很高兴看到有人努力保持良好的清洁用户界面。荣誉,更多的人应该这样做。但是,我建议不要以这种方式解决问题。你冒着试图强迫一个元素做一些它不想做的事情的风险。即使您找到了解决方法,它最终可能会让您进入跨浏览器测试地狱,或者只是停止使用新的浏览器版本。

我建议用JQuery或类似的可脚本化的SELECT小部件替换替换它,例如http://filamentgroup.com/lab/jquery_ui_selectmenu_an_aria_accessible_plugin_for_styling_a_html_select/。这将为您提供通过JavaScript调整显示所需的所有灵活性。

答案 1 :(得分:0)

这是一种相当简单的方法...使用更改/输入,当它聚焦时,将文本重置为年前的任何内容。

似乎在我测试过的所有浏览器中运行良好。问题是无论你做什么,你总是要改变所选元素的文本值,没有办法解决这个问题。无需在此部署 - http://jsfiddle.net/CTwJy/

即可自行测试
<select name="month_selection" id="month_selection">
    <optgroup label="2012">
        <option value="1">January</option>
    </optgroup>
    <optgroup label="2011">
        <option value="1">January</option>
        <option value="2">February</option>
    </optgroup>
</select>

<script type="text/javascript">
function attach(ele, evt, cb) { ele.addEventListener ? ele.addEventListener(evt, cb) : ele.attachEvent('on' + evt, cb); }
function evSupported(ele, evt) { return ((('on'+evt) in ele) ? true : (function(ele, evt) { ele.setAttribute('on'+evt, 'return;'); return (typeof ele['on'+evt] == 'function'); })()); };

var selectBox = document.getElementById('month_selection');

attach(selectBox, (evSupported(selectBox, 'input') ? 'input' : 'change'), function() {
    this.options[this.selectedIndex].innerText += ' ' + this.options[this.selectedIndex].parentNode.label;
    this.blur();
});
attach(selectBox, 'focus', function() {
    for (var i = 0; i < this.options.length; i++) {
        this.options[i].innerText = this.options[i].innerText.split(' ')[0];
    }
});
</script>

答案 2 :(得分:-2)

这未经过测试,因此可能无效或可能有错误(例如,它可能会永久更改选项的标签),但也许它会为您提供一些见解。

<script type="text/JavaScript">
    function changeLabel()
    {
        var dropDown = document.getElementById("selMonth");
        dropDown.options[dropDown.selectedIndex].label += " "+ dropDown.options[dropDown.selectedIndex].parentNode.label;
    }
</script>

<select name="month_selection" id="selMonth" onchange="changeLabel()"> 
    <optgroup label="2012"> 
        <option value="1">January</option> 
    </optgroup> 
    <optgroup label="2011"> 
        <option value="1">January</option> 
        <option value="2">February</option>