2013-10-29 93 views
-2

我想發送一個JS變量到特定的網頁。以下是我的代碼。通過href鏈接發送JS變量

<script> 
function hello() 
{ 
var data="hello"; 
<a href="www.mytestsite.com?var="' +data +'>Send now</a> 
} 
</script> 

的hello()函數被調用時,一個提交按鈕被點擊user.But當我點擊鏈接「現在發送」。這是結果www.mytestsite.com?var=。那是數據沒有得到追加到鏈接。我在這裏錯了什麼?

在此先感謝。

+1

你不能簡單地嵌入在JavaScript中的錨標記。 – ComFreek

回答

1

的Java腳本代碼無效。 它應該是這樣的:

<script> 
    function hello() 
    { 
      var data="hello"; 
      document.write('<a href="www.mytestsite.com?var='+data+'">Send now</a>'); 
    } 
    </script> 
2

如果JavaScript僅在按鈕單擊時執行,並且您希望重定向用戶,則不需要錨定標記。只需重定向用戶。

function hello() { 
    var data = "foobar"; 
    window.location.href = "http://example.com?data=" + data; 
} 
+0

我想重定向用戶,當他們點擊「立即發送鏈接」,而不是點擊按鈕。 – Ravikanth

+1

然後在鏈接上設置事件處理程序,並將鏈接的href設置爲'#'。 – xbonez

0

試試這個

<script> 
function hello() 
{ 
    var data="hello"; 
    document.write("<a href='www.mytestsite.com?var=" + data + ">Send now</a>"); 
} 
</script> 

,或者如果你想要把鏈接與一些html元素

document.getElementById('DIV').innerHTML = "<a href='www.mytestsite.com?var=" + data + ">Send now</a>"; 
0

剛上定位標記的onclick屬性添加function(like hello())

onclick="yourFunction();return false;"