Javascript编码帮助。跳过某段代码

时间:2015-08-30 05:21:58

标签: javascript function

我正在尝试编写Web应用程序代码,但我遇到了一个小问题。 在代码的顶部,屏幕周围有一个移动项目。我调用该项在代码开头随机移动屏幕。但是当我点击一个按钮时,它会停止。所以我做的是我在点击它时创建了一个函数,它将x,y,z捕获到函数中的局部变量中。然后我将这些固定的x,y,z值输入到项目中,使其保持静止,但出于某种原因,我认为它被顶部代码覆盖并仍然继续移动。当某个特定的函数运行时,有没有办法在代码的顶部跳过一行代码?

我正在谈论的代码

function motionUpdate()
{
  xvalues= //huge code which is obtained from device sensors
  yvalues= //huge code which is obtained from device sensors
  zvalues= //huge code which is obtained from device sensors

  //There are two objects that move id1 and id2. When clicking on button id2 should stop
  ui.elememenTranslate(xvalues,yvalues,zvalues,"id1") //moves according to x,y,z location
  ui.elememenTranslate(xvalues,yvalues,zvalues,"id2")
}
self.Click = function()
{
  var localX = xvalues;
  var localY = yvalues;
  var localZ = yvalues;
  ui.elememenTranslate(xvalues,yvalues,zvalues,"id2")
}

2 个答案:

答案 0 :(得分:1)

使用全局变量作为运行代码的条件。例如:

var run_code = true;

然后在代码中:

function motionUpdate()
{
    if(run_code) // if run_code is true, else skip this part
    {
    ....
    }
}

在某些条件下的其他部分代码中,按要求设置:

run_code = false;

设置完成后,将跳过上面的代码。

答案 1 :(得分:0)

扩展Ashad Shanto的评论,如果点击了按钮,你可以使用一个标志来保存。

// Save if the button was clicked
var id2IsStopped = false;

function motionUpdate(){
     ...
    ui.elememenTranslate(xvalues,yvalues,zvalues,"id1") //moves according to x,y,z location

    // Don't run translate if the button was clicked
    if(!id2IsStopped){
        ui.elememenTranslate(xvalues,yvalues,zvalues,"id2")
    }
}

self.Click = function(){
    ...
    ui.elememenTranslate(xvalues,yvalues,zvalues,"id2");

    // Record that the button was clicked
    id2IsStopped = true;
}

这将记录单击的按钮并停止在id2上运行翻译。但是,如果你想切换id2的移动,你只需要切换标志的值:

// Previously: id2IsStopped = true;
id2IsStopped = !id2IsStopped;