HTML DOM 錨文字屬性
與錨標籤 (<a>) 關聯的 HTML DOM text 屬性指定錨標籤的文字部分。
例如,<a href=”www.google.com”>Google</a>。這裡的文字部分是 Google。使用 text 屬性,我們可以獲取或更改錨文字的值。
語法
以下是語法 -
返回 text 屬性 -
anchorObject.text
設定 text 屬性 -
anchorObject.text = sometext
示例
我們來看一個錨文字屬性的示例 -
<!DOCTYPE html> <html> <body> <p><a id="Anchor" href="http://www.examplesite.com">Example site</a></p> <p>Click the button below to change the text content of the link above.</p> <button onclick="ChangeText()">Click it</button> <button onclick="GetText()">Get Text</button> <p id="Sample"></p> <script> function ChangeText() { document.getElementById("Anchor").text = "Click here to open examplesite"; } function GetText(){ var x=document.getElementById("Anchor").innerHTML; document.getElementById("Sample").innerHTML=x; } </script> </body> </html>
輸出
這將生成以下輸出 -
點選“單擊它”後 -
點選“獲取文字”後 -
在以上示例中 -
我們以“示例網站”作為連結文字採用錨標籤
<p><a id="Anchor" href="http://www.examplesite.com">Example site</a></p>
然後,建立兩個按鈕“單擊它”和“獲取文字”以分別執行 ChangeText() 和 GetText() 函式。
<button onclick="ChangeText()">Click it</button> <button onclick="GetText()">Get Text</button>
ChangeText() 函式將錨文字從“示例網站”更改為“單擊此處開啟示例網站”,而 GetText() 函式從連結中獲取錨文字(ID 指定為錨),並將其顯示在與之關聯的 ID 為 Sample 的段落中。
廣告