【问题标题】:help constructing while loop帮助构建while循环
【发布时间】:2011-02-07 20:39:26
【问题描述】:

您好,我正在尝试创建一个 while 循环,但到目前为止,我对放入其中的内容有疑问:

function showSports(obj)
{
    var groupId = obj.id.substring(0, 1);
    var indx = obj.id.substring(obj.id.indexOf('_') + 1);
    var id = indx.substring(0, indx.length + 1);
    var displayInfo = false;
    while (displayInfo)
    {
        if (indx == 1)
        {
            show('footballInfo');
            hide('soccerInfo');
            hide('baseballInfo');
        }
        if (indx == 2)
        {
            show('soccerdInfo');
            hide('baseballInfo');
            hide('footballInfo');
        }
        if (indx == 3)
        {
            show('baseballInfo');
            hide('footballInfo');
            hide('soccerdInfo');
        }
        displayInfo = true;
    }
}

它应该能够遍历下面的链接并根据选择的链接显示/隐藏。

<a id='1link_1a' title="football Tab" onclick='showSports(this);'>
  <span>FootBall</span>
</a>
<a id='1link_1b' title="soccer"
onclick='showSports(this); changeTab(this);'>
  <span>Soccer</span>
</a>
<a id='1link_1c' title="baseball" onclick='showSports(this);'>
  <span>Baseball</span>
</a>

【问题讨论】:

  • 您能描述一下究竟“不工作”的原因吗?
  • 你有 while (displayInfoTab) 但没有声明那个变量。
  • displayInfoTab 应该是 displayInfo

标签: javascript loops while-loop


【解决方案1】:

我不明白您对 while 语句的使用。也许你正在考虑一个 switch 语句。

function showSports(obj)
{
    var groupId = obj.id.substring(0, 1);
    var indx = obj.id.substring(obj.id.indexOf('_') + 1);
    var id = indx.substring(0, indx.length + 1);

    switch (indx)
    {
        case 1:
            show('footballInfo');
            hide('soccerInfo');
            hide('baseballInfo');
        break;
        case 2:
            show('soccerdInfo');
            hide('baseballInfo');
            hide('footballInfo');
        break;
        case 3:
            show('baseballInfo');
            hide('footballInfo');
            hide('soccerdInfo');
        break;
    }
}

【讨论】:

【解决方案2】:

RightSaidFred 是正确的,听起来您打算使用 switch。另一点是该行:

var id = indx.substring(0, indx.length + 1);

会有索引越界错误。我想你正在考虑这样做:

var id = indx.substring(0, indx.length - 1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2018-06-20
    • 2010-11-29
    • 2011-05-14
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多