2016-01-20 28 views
0

我的html代碼:從Javascript返回值到HTML <a href>標籤

<a id="abc_1" name="link_1" href="" 
        onclick="updateLink(this.id);">Test Link</a> 

我的JavaScript函數是這樣的:

function updateLink(a){ 
var newurl = document.location.href "+" + a.valueOf(); 
return newurl; 
} 

我想將用戶定向到該NEWURL上點擊的鏈接。 如何做到這一點? 注:我看過一個使用<div>標籤的例子,但我需要它在<a href>標籤中。

+2

'location.href = newurl'應該工作 – tymeJV

+0

你是不是與該功能對它們進行重定向。像@tymeJV說你需要設置頁面的location.href。 –

+0

我刪除了返回並試圖location.href = newurl,但它不工作,如果我做alert(newurl),它會顯示更新的url,但頁面只是刷新。 – User2403

回答

1

我認爲錨屬性ID或名字包含了新的URL信息而改變。

看看這個例子:

<a href="#" id="abc_1" name="link_1" onclick="updateLink(this)" >Test Link</a> 

<script> 
function updateLink(a) { 
    var newurl = ""; 

    //You could retrieve the object name 
    newurl = a.getAttribute("name"); 

    //Or, retrieve the id 
    newurl = a.getAttribute("id"); 

    //redirect 
    location.href = newurl; 
} 
</script> 
+0

亞,它的工作,但我使用document.location.href而不是location.href,它可以是一個問題?有什麼不同??我是新來的,想要知道最好的使用 – User2403

+0

請參閱http://stackoverflow.com/questions/2652816/what-is-the-difference-between-document-location-href-and-document-location –

1

一種方法是href屬性從單擊處理

window.updateLink = function (a){ 
 
     // This won't work in this example because this frame 
 
     // is set 'X-Frame-Options' to 'SAMEORIGIN'. 
 
     // However, the error message displayed in the console is indication 
 
     // that it indeed tried to navigate to the URL I gave it 
 
     a.setAttribute('href', 'http://www.google.com?q=' + a.id); 
 
    }
<a href="#" id="http://www.google.com" onclick="updateLink(this)" >Test</a>

+0

它不起作用,頁面刷新同一鏈接。 – User2403

+0

雅,它的工作正常。即使tymeJV的建議(在評論中)也在起作用。我也發現了我的錯誤,我沒有使用href =「#」。對不起,我是網絡開發新手,非常感謝。 – User2403

+0

它應該是工作,我添加了一個例子,我改變了href,你會看到頁面重新加載(到一個空白頁面) –