动态显示和隐藏选择菜单

jQuery: Dynamically show and hide select menu

本文关键字:菜单 选择 隐藏 动态显示      更新时间:2023-09-26

我希望用户在点击一个单词时能够做出一个新的选择。我已经编写了一个几乎完美的代码:

http://jsfiddle.net/24rjN/

HTML:

<p>Your current town of stay:</p>
<p id="profile_town_selected">Vienna</p>
<select id="profile_town_dropdown" style="display:none">
        <option selected="true" style="display:none;">select town</option>
    <option>Barcelona</option>
    <option>London</option>
    <option>Berlin</option>
</select>

JS:

function showOptions(old_selection, dropdown) {
    old_selection.hide();
    dropdown.show();
    dropdown.on('change', function() {
        var new_selection = $(this).val();
        $(this).hide();
        old_selection.text(new_selection).show();
    });
}
$('#profile_town_selected').on('click', function() {
        var old_selection = $(this);
        var dropdown = $('#profile_town_dropdown');
        showOptions(old_selection, dropdown);
    });

我的问题:当用户决定坚持当前选择时,选择菜单不会消失。例如,当用户点击Vienna时,选择菜单就会出现。如果他再次点击Vienna,选择菜单不会消失。只有当他选择一个不同于当前选择的城镇时,它才会消失。我需要如何修改代码,以实现选择菜单也消失时,用户自发地决定不选择另一个城镇?

JS:

    dropdown = $('#profile_town_dropdown');
clickCount = 0;
previousValue = '';
dropdown.on('click', function (event) {
    if (clickCount == 0) {
        clickCount++;
        return;
    } else {
        if ($(this).val() == previousValue) {
            $(this).hide();
            var new_selection = $(this).val();
            old_selection.text(new_selection).show();
            clickCount = 0;
        }
    }
    console.log(event);
});
dropdown.on('change', function () {
    var new_selection = $(this).val();
    $(this).hide();
    previousValue = new_selection;
    old_selection.text(new_selection).show();
}).focus();
$('#profile_town_selected').on('click', function () {
    old_selection = $(this);
    old_selection.hide();
    dropdown.show();
});
$('#profile_town_dropdown').on('blur', function () {
    old_selection.show();
    $(this).hide();
});
http://jsfiddle.net/robschmuecker/24rjN/1/

dropdown.on('change', function()改为dropdown.on('blur', function()

试试这个:

function showOptions(old_selection, dropdown) {
        old_selection.hide();
        dropdown.show();
        dropdown.on('blur', function() {
            var new_selection = $(this).val();
            $(this).hide();
            old_selection.text(new_selection).show();
        });
    }
$('#profile_town_selected').on('click', function() {
            var old_selection = $(this);
            var dropdown = $('#profile_town_dropdown');
            showOptions(old_selection, dropdown);
        });