javascript - 通过 if else 语句显示具体的输出

标签 javascript

我正在研究如何根据用户输入在 dat.gui 界面的下拉列表中显示条目,但我遇到的问题与 dat.gui 编程无关,而是我缺乏 javascript 技能.

我有两个列表,一个显示 Starsystem01 作为名称。 另一个是 Planets,它显示了 Starsystem 中的特定行星。 我该如何编写此语句,以便这两个数组仅在选择 0 或 1 时显示?

var jumpSwitcher = 0;

    this.Starsystems = 'dat.gui';
//Starsystem list
    gui.add(this, 'Starsystems', ['0', '1']).onChange(function(value) {
        if (value === '1') {
            jumpSwitcher = 1;
        }
    });

    this.Planets = 'dat.gui';
//if the var jumpSwitcher is 0, display these variables in the Planets array.
    if (jumpSwitcher === 0) {
        Planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'];
    } 

//if the jumpSwitcher is 1, meaning if the user has clicked on "1" under the Starsystem, show these planets. 
    else if (jumpSwitcher === 1) {
        Planets = ['Ilos', 'Tuchanka', 'Palaven', 'Illium'];
    }

    gui.add(this, 'Planets', Planets).name("Planets in this system").onChange(function(value) {
    });

我会说这应该可行,但不知何故却行不通。当我简单地使语句中的条件类似于 if (1>0) {show 1} else {show 2} 时,它就会发生。

附言:

var jumpSwitcher = 1;  
    this.Starsystems = 'dat.gui';
gui.add(this, 'Starsystems', ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']).onChange(function(value) {

    jumpSwitcher = +value;

});

this.Planets = 'dat.gui';

switch (jumpSwitcher) {
    case 1:    
        gui.add(this, 'Planets', ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']).name("Planets in this system").onChange(function(value) {

        });    

        break;
    case 2:    
        gui.add(this, 'Planets', ['Ilos', 'Tuchanka', 'Illium', 'Palaven']).name("Planets in this system").onChange(function(value) {

        });

        break;    
}

最佳答案

您需要重置jumpSwitcher

改变

if (value === '1') {
    jumpSwitcher = 1;
}

jumpSwitcher = +value;

这会将 jumpSwitcher 设置为一个数值。

另一种解决方案可能是改变数组内部的值以获取数值而不是字符串,如果这些值是连接的。

gui.add(this, 'Starsystems', [0, 1]).onChange(function(value) {
//                           ^^^^^^
    jumpSwitcher = value;
});

关于javascript - 通过 if else 语句显示具体的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40238900/

相关文章:

javascript - 捕获按钮上所有单击的跨浏览器方式是什么?

javascript - hasData 无法附加到段落

JAVASCRIPT:如何获取页面中链接的 URL?

javascript - Express 无法读取 PUT 请求中 req.data 的属性值

javascript - 选择 FromDate 和 ToDate 时启用提交按钮

javascript - 如何: test if client is a "desktop terminal"

javascript - 滑动条触发器不起作用(又名滑动条)

javascript - 在 Javascript 中添加上一个按钮

javascript - YouTube 播放器 API : How to get duration of a loaded/cued video without playing it?

javascript - 如何清除函数中的 setInterval