2014-05-01 94 views
-2

我想合併兩個html/css-js代碼,但它不起作用。html - javascript代碼合併

的第一個HTML代碼是在點擊一個簡單的按鈕上的文字改爲:

<html> 
<head> 

<script type="text/javascript"> 

function myTest(btnID) 
{ 
document.getElementById(btnID).value="After"; 
} 

</script> 

</head> 
<body> 

<input type="button" name="toggleBtn" id="toggleBtn" onclick="myTest('toggleBtn')" value="Before" > 

和JavaScript代碼,我想與合併:

<script type="text/JavaScript"> 
<!-- 
redirectTime = "5000"; 
redirectURL = "http://cpanel.hostinger.ae"; 
function timedRedirect() { 
setTimeout("location.href = redirectURL;",redirectTime); 
} 
// --> 
</script> 

<div style="background-color:green;padding:5px;width:110px;cursor:pointer;" 
onclick="JavaScript:timedRedirect()"> 
By M.A JS Code 
</div> 

我怎樣才能讓上單擊更改按鈕文本,然後通過定時器重定向頁面?

回答

0

你的意思是這樣嗎?

<html> 
<head> 

<script type="text/javascript"> 

function myTest(btnID) 
{ 
    document.getElementById(btnID).value="After"; 

    redirectTime = 5000; 
    redirectURL = "http://cpanel.hostinger.ae"; 
    (function(redirectTime, redirectURL) { 
     setTimeout("location.href = redirectURL;",redirectTime); 
    })(redirectTime, redirectURL); 
} 

</script> 

</head> 
<body> 

<input type="button" name="toggleBtn" id="toggleBtn" onclick="myTest('toggleBtn')" value="Before" > 
+0

在您的代碼'timedRedirect()'將永遠不會被執行。我懷疑,這是,OP想要什麼。 – Sirko

+0

是的,我剛剛意識到,他只是要求代碼合併,這是我做的,但我解決了這個問題(將代碼移出函數,因爲它感覺不必要) – Colandus

+0

這也不會工作。 'setTimeout()'回調將在全局範圍內執行,其中'redirectURL'變量未知。在這裏更好地使用匿名函數。 – Sirko

1

添加額外的代碼已經工作,你必須:jsFiddle Example

<html> 
    <head> 

     <script type="text/javascript"> 

      function myTest(e) { 
       e.value = "After"; 
       redirectTime = "5000"; 
       redirectURL = "http://cpanel.hostinger.ae"; 
       setTimeout(function(){location.href = redirectURL;}, redirectTime); 
      } 

     </script> 

     </head> 
     <body> 

      <input type="button" name="toggleBtn" id="toggleBtn" onclick="myTest(this);" value="Before"> 

     </body> 
</html>