2014-09-05 142 views
-3

我正在嘗試調用一個javascript函數,該函數根據a href標記中的當前日期時間生成變量。該變量將被添加到URL的末尾。在<a href></a>函數中調用Javascript函數

但是,它不工作,因爲我想要它。我需要做些什麼才能使其正常工作?

<script type="text/javascript"> 

    function newNumber() { 
     c = (new Date()).getTime(); 
     return c; 
    } 

</script> 

<a href="https:www.something.com&id= + javascript:newDisney()" >Click Here</a> 
+1

newDisney()或newNumber()? – Roland 2014-09-05 22:50:14

+0

對不起newNumber()犯了一個錯誤,沒有注意到 – 2014-09-05 22:55:59

+0

你能編輯你的問題來解決這個錯誤嗎? – Roland 2014-09-06 13:22:22

回答

1

這裏是你如何在現代瀏覽器做:

JS

function myUrlFunction(e){ 
e.preventDefault(); 
window.location='https://www.something.com/?id='+Date.now() 
} 
function myUrlSetup(){ 
document.getElementById('myLink').addEventListener('click',myUrlFunction,false); 
} 
window.addEventListener('load',myUrlSetup,false); 

HTML

<a href="#" id="myLink">Click Here</a> 

演示

http://jsfiddle.net/xv09rjsn/

,如果您有任何問題,只是問

正如在評論中提到...

,如果你想在這裏所有的瀏覽器支持的代碼,反正有寫這個無限的方式。 「#」是相對的在下面的代碼...

function myUrlFunction(){ 
window.location='https://www.something.com/?id='+(new Date().getTime()); 
return false 
} 
function myUrlSetup(){ 
document.getElementById('myLink').onclick=myUrlFunction 
} 
window.onload=myUrlSetup 

內HTML屬性您shouuld無法使用JavaScript ...創建合適的功能,這是easely mantainable,至極做正確的算法爲你的目的。並將其應用於鏈接,按鈕,圖像,事件!或任何你想要的。

,如果你真的想raplace的元素href屬性您重定向之前的不僅僅是更換myUrlFunction

function myUrlFunction(){ 
var link=document.getElementById('myLink'); 
link.href='https://www.something.com/?id='+(new Date().getTime()); 
link.click();// works on some browsers. 
return false 
} 

,如果您有任何qurestions只問。

+1

你不應該使用'href =「#」'。當JavaScript失敗時,您應該有一個合理的默認URL。 – Quentin 2014-09-05 22:51:49

+0

是的......你的權利;) – cocco 2014-09-05 22:52:26

-1

有很多方法可以做到這一點。例如: HTML

<a id="ref" href="https:www.something.com&id=" >Click Here</a> 

的JavaScript

var ref = document.getElementById("ref"); 
ref.href += newNumber(); 
alert(ref.href); 

function newNumber(){ 
    c = (new Date()).getTime(); 
    return c; 
} 

檢查此鏈接jsfiddle看到一個工作的例子。希望它有用!

相關問題