如何使用JavaScript動態地將href
屬性添加到鏈接?如何使用JavaScript動態地將「href」屬性添加到鏈接?
我基本上想要動態地(即當用戶點擊網站中的特定圖像時)將href
屬性添加到<a></a>
。
所以從:
<a>Link</a>
我需要去:
<a href="somelink url">Link</a>
如何使用JavaScript動態地將href
屬性添加到鏈接?如何使用JavaScript動態地將「href」屬性添加到鏈接?
我基本上想要動態地(即當用戶點擊網站中的特定圖像時)將href
屬性添加到<a></a>
。
所以從:
<a>Link</a>
我需要去:
<a href="somelink url">Link</a>
var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"
我假設你知道如何讓DOM對象的<a>
元素(使用document.getElementById
或其他一些方法)。
添加任何屬性,只需使用setAttribute方法DOM對象:
a = document.getElementById(...);
a.setAttribute("href", "somelink url");
我知道這已經回答了,但由於這篇文章幫我拿我的解決方案,我想後。
本來,我想
<a href='somelink' class='button-css'>Click Me</a>
,這幾乎工作。文本有點偏離中心,並且不是很清楚。我然後嘗試:
"<a href='SomeLink'><input type='button' class='button-css' value='Button Text' /></a>"
我的按鈕看起來不錯,鏈接工程。
document.getElementById('link-id').href = "new-href";
我知道這是舊的文章,但這裏有一個一行,可能更適合一些人。
首先,嘗試將<a>Link</a>
更改爲<span id=test><a>Link</a></span>
。
然後,添加這樣的事情在你調用JavaScript函數:
var abc = 'somelink';
document.getElementById('test').innerHTML = '<a href="' + abc + '">Link</a>';
這樣的鏈接看起來就像這樣:
<a href="somelink">Link</a>
有趣。我不知道你可以直接訪問屬性作爲字段(比較我的解決方案,使用`setAttribute`)。有人知道這種方法是否標準? – mgiuca 2011-01-14 08:53:32
謝謝大家 - 兩種方式都有效。 – Pavel 2011-01-14 08:56:38
我認爲在DOM元素href是一個屬性,你可以直接由el.href設置。相反,setAttribute(el,attr)用於將一些自定義屬性添加到特定的DOM元素,因此在這種情況下不需要使用它來設置std。 attr – stecb 2011-01-14 08:57:07