JavaScript-如何循环三个项目

时间:2018-12-13 01:50:42

标签: javascript javascript-events javascript-objects

我在移动ar应用程序中有三个资产,需要在点击时进行交换,以便每个点击都可以关闭当前项目的可见性并打开下一个项目的可见性。我可以监控点击并订阅该事件。我可以将资产设置为*.hidden = truefalse,但是我不确定通过资产交换所需的逻辑。

我会为水龙头创建计数功能(限制为三个吗?),然后根据生成的隐藏/取消隐藏数量使用if / then?

我以前确实只用Python和一些js编写过脚本,但是“代码很好奇”,对于这种难题,我将在JavaScript中使用哪些约定?成功会是什么样?

2 个答案:

答案 0 :(得分:0)

下面是一个示例,该示例说明如何使用Javascript单击一组资产(在本例中为input元素),一次仅显示一个资产:

var ix = 0;

var assets = ["x1","x2","x3"].map(
  function(x) {return document.getElementById(x);}
);

function showNextAsset() {
  assets[ix++].style.display = "none";
  assets[ix = (ix < assets.length) ? ix : 0].style.display = "block";
}
<form onclick="showNextAsset(); return false;">

<input id="x1" value="foo">
<input id="x2" value="bar" style="display:none">
<input id="x3" value="toto" style="display:none">

</form>

答案 1 :(得分:0)

抬起头来,我终于想出了如何做我需要做的事情,它看起来像这样:

const TouchGestures = require('TouchGestures');
const Scene = require('Scene');
const D = require('Diagnostics');

//scene assets:
const asset1 = Scene.root.find('plane0');
const asset2 = Scene.root.find('plane1');
const asset3 = Scene.root.find('plane2');
//assets put into array:
const myArray = [asset1,asset2,asset3];
//initial visibility state for assets:
var hideStates = [0,1,1];
//set initial visibility:
hide(myArray,hideStates);



//MAIN EVENT___________________________________________________________________________________
TouchGestures.onTap().subscribe(function (gesture) { // cycle visibility for assets on event

    var hideStates = [1,1,1];
    hide(myArray,hideStates);
    unHide(myArray);

});

//_____________________________________________________________________________________________

//this will move through an array one step at a time, returning the index...
var cycler = {
    current: -1,
    cycle: function(arr) {
        if (this.current == arr.length -1) {
            this.current = 0;
        } else {
            this.current++;
        }
        return this.current;
    }
};


function hide(assets,states) {
    for (var i = 0; i <assets.length; i++) {
        assets[i].hidden = states[i];
    }
};

function unHide(assets) {
    var unhide = cycler.cycle(myArray);
    myArray[unhide].hidden = 0;
};

不确定这是否是最好的做事方法,但是它有效!