2017-12-19 9 views
-3

5 초 카운트 다운으로 페이지를 리디렉션하려고하지만 사용자가 countdwn을 취소하고 페이지에 머물러 있어야합니다. 여기 내 HTML카운트 다운 및 취소 옵션을 사용하여 Javascript로 리디렉션 페이지

var targetURL="http://javascriptkit.com"; 

var countdownfrom=10; 


var currentsecond=document.redirect.redirect2.value=countdownfrom+1; 
function countredirect(){ 
if (currentsecond!=1){ 
currentsecond-=1; 
document.redirect.redirect2.value=currentsecond; 
} 
else{ 
window.location="WWW.google.com"; 
return; 
} 
setTimeout("countredirect()",1000) 
} 

countredirect(); 

참고 자바 스크립트 여기

<form name="redirect"> 
<center> 
<font face="Arial"><b>You will be redirected to the script in<br><br> 
<form> 
<input type="text" size="3" name="redirect2"> 
</form> 
seconds</b></font> 
</center> 

하고있다 : 나는 실제로 팝업 상자에하고 싶었던와 함께 버튼을 취소

+0

그래서 발견 한 그 오래된 코드에 어떤 문제가 있습니까? 문제를 해결하기 위해 시도한 것은 무엇입니까? [Java는 JavaScript가 아닙니다. 이에 따라 주제 태그를 편집했습니다. ] 당신은 어떤 jQuery도 가지고 있지 않습니다.] –

답변

-1

당신 사항 clearTimeout()를

사용할 수 있습니다

HTML :

<form name="redirect"> 
<center> 
<font face="Arial"><b>You will be redirected to the script in<br><br> 
<input type="text" size="3" name="redirect2"> 
<input type="button" id="CancelButton" value="Cancel" onclick="javascript:cancelRedirect();" > 
seconds</b></font> 
</center> 
</form> 

JS :

var targetURL="http://javascriptkit.com"; 

var countdownfrom=10; 
var timeoutHandler; 
var currentsecond=document.redirect.redirect2.value=countdownfrom+1; 

function countRedirect(){ 
    if (currentsecond!=1){ 
     currentsecond-=1; 
     document.redirect.redirect2.value=currentsecond; 
    } 
    else{ 
     window.location="http://www.google.com"; 
     return; 
    } 
    timeoutHandler = setTimeout(countRedirect,1000) 
} 

function cancelRedirect(){ 
    clearTimeout(timeoutHandler); 
} 
countRedirect(); 
+0

답변 해 주셔서 감사합니다. 아마 왜 여기 있는지 확인해 주시겠습니까? 카운트 다운 https://jsfiddle.net/#&togetherjs=7BshHSfrj8 –

+0

지금 바이올린에서 작동하도록 업데이트했습니다. "countRedirect()"가 따옴표 안에있는 것이 좋습니다. –

+0

모든 코드는 완전히 쓸모가 없습니다. 하나의 타이머 만 설정할 수 있습니다. –

1

코드가 절대 불합리한 것입니다. 매 초마다 다른 카운트 다운을 시작하기 위해 카운트 다운하는 이유는 무엇입니까? 당신은 단지 X 초 타이머를 설정하고 당신이 원하는 때마다 그것을 지울 수, 코드의 흐름이 완전히 불필요 :

var countdown = setTimeout(redirect, redirectTime) 

함수 "재"를 호출하는 시간 제한을 설정하는 시간 "redirectTime"일단 경과.

당신은 당신의 리디렉션 기능을 정의해야

var newLocation = “...” 
function redirect(){ 
    window.location = newLocation 
} 

을 그리고 지금 당신이 가진 타이머를 취소 할 수 있습니다

function clearCountdown(){ 
    clearTimeout(countdown) 
} 

는 사용자가 버튼을 클릭하거나 수행 할 때 바인딩 할 수 있습니다 어떤 네가 원해.

당신은 jQuery를 조금 추가하는 경우 :

$(document).ready(function(){ 
    var countdown = setTimeout(redirect, redirectTime) 
} 

그리고 ...

$(“#myButton”).click(clearCountdown) 

참고 : 코드 및 워크 플로우 간단하게 유지합니다. DRY (스스로 반복하지 말라)와 "simple is complex보다 낫다."(이 마지막 것은 Python의 철학 요리법에서 나온 것입니다.)

+0

나는 아래 유권자에게 왜 그가 downvoted 설명을 남길 싶습니다. 나는 그것이 어리석은 것이기 때문에 복수가 아니길 바란다. –