【问题标题】:Applying functions to string variables? [closed]将函数应用于字符串变量? [关闭]
【发布时间】:2014-06-15 22:46:45
【问题描述】:

我有一个包含几行/按钮的垂直任务栏(每个类 .slidebar 和不同的 ID #start、#sprache、#modus 等)。当我将鼠标悬停在每一行/按钮上时,应该会出现一个不同的弹出菜单(例如 #start_fly 用于按钮 #start)。不幸的是,它没有。我想那是因为我正在尝试将函数应用于字符串变量,如下所示:

flyout_id = "$('#"+id_name+"')"; //$('#start_fly')
flyout_id.css({//some code
});

这是完整的代码:

$(document).ready(function () {
 $('.slidebar').each(function () {
    var startOffset = $(this).position();
    var ID = $(this).attr('id');
    var id_name, flyout_id;
    switch (ID) {
    case 'start':
        id_name = "start_fly";
        break;
    case 'sprache':
        id_name = "sprache";
        break;
    case 'modus':
        id_name = "modus_fly";
        break;
    case 'teilen':
        id_name = "teilen_fly";
        break;
    case 'info':
        id_name = "info_fly";
        break;
    }

    flyout_id = "$('#" + id_name + "')"; //$('#start_fly') in 1. case 'start'
    $(this).bind({
        mouseenter: function () {
            flyout_id.css({
                position: 'fixed',
                top: startOffset.top + 8,
                left: $(this).offset().left - flyout_id.width()
            });
            flyout_id.show();
        },
        mouseleave: function () {
            flyout_id.hide();
        }
    });
    flyout_id.bind({
        mouseleave: function () {
            $(this).hide();
        },
        mouseenter: function () {
            $(this).show();
        }
    });
 });
});

【问题讨论】:

  • 试试这个flyout_id = $('#' + id_name);

标签: jquery string variables switch-statement each


【解决方案1】:

这是一个字符串:

flyout_id = "$('#"+id_name+"')";

大概想要做的是创建一个 jQuery 对象:

flyout_id = $("#"+id_name);

另外请注意,由于您的所有 switch 语句都是在 ID 的末尾添加“_fly”(sprache 的情况除外),您可以将其替换为:

id_name = ID;
if (ID !== "sprache") {
    id_name = ID + "_fly";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2020-11-23
    • 2014-06-28
    相关资源
    最近更新 更多