两次点击之间的差异在这段代码上并不顺利

时间:2016-11-03 08:00:10

标签: javascript click addeventlistener

我是javascript的新手,这就是我问这个问题的原因。如果在按下“键”后9秒的时间间隔内按下“哈希”键,我只想要“解锁”警报,但它没有按预期工作,任何人都可以帮助我吗?

public static void doLogout(){          
            WebDriverWait wait = new WebDriverWait(driver, 5);          
            wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='responsiveHeader']/div[1]/div[1]/ul/li[4]/a/i"))).click();
            wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Sign Out"))).click();
}
document.getElementById("key").addEventListener("click",function(){
alert("enter # to unlock");  
var time = (new Date()).getTime();
  //alert(time);
});

document.getElementById("hash").addEventListener("click",function(){
  var keytime = (new Date()).getTime();
    //alert(keytime);
   var diff = time - keytime;
  alert(diff);
  if(diff <= 9000){
    alert("unlocked");  
  }
  else{
   alert("try again");  
  }
  
  });

3 个答案:

答案 0 :(得分:0)

您在time点击监听器的范围内初始化了#key。它无法到达外面。

将其设置为全局变量。

Variable scope documentation

&#13;
&#13;
 
var time = 0;

document.getElementById("key").addEventListener("click",function(){
  alert("enter # to unlock");  
  time = (new Date()).getTime();
  //alert(time);
});

document.getElementById("hash").addEventListener("click",function(){
  var keytime = (new Date()).getTime();
    //alert(keytime);
   var diff = time - keytime;
  alert(diff);
  if(diff <= 9000){
    alert("unlocked");  
  }
  else{
   alert("try again");  
  }
  
  });
&#13;
<button id="key">key </button>
<button id="hash">#</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

time应该是一个全局变量,以便hash事件监听器可以访问它。

&#13;
&#13;
var time = Infinity;
document.getElementById("key").addEventListener("click",function(){
alert("enter # to unlock");  
time = (new Date()).getTime();
  //alert(time);
});

document.getElementById("hash").addEventListener("click",function(){
  var keytime = (new Date()).getTime();
    //alert(keytime);
   var diff = time - keytime;
  alert(diff);
  if(diff <= 9000){
    time = Infinity;
    alert("unlocked");  
  }
  else{
   alert("try again");  
  }
  
  });
&#13;
<button id="key">key </button>
<button id="hash">#</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

时间是本地变种。

要在其他函数中访问它,你应该创建一个像这样的全局变量:

var time;
document.getElementById("key").addEventListener("click",function(){
alert("enter # to unlock");  
time = (new Date()).getTime();
  //alert(time);
});

document.getElementById("hash").addEventListener("click",function(){
  var keytime = (new Date()).getTime();
    //alert(keytime);
   var diff = time - keytime;
  alert(diff);
  if(diff <= 9000){
    alert("unlocked");  
  }
  else{
  alert("try again");  
 }

  });