DIV CSS 佈局教程網

JS取得網頁圖片name屬性的方法
編輯:關於JavaScript     

本文示範如何取得圖片元素的 name 屬性。

寫法和讀取其他屬性一致:先定位元素,再存取 .name。

 <!DOCTYPE html> <html> <body> <img id="compman" name="compman" src="compman.gif" alt="Computerman" width="107" height="98"> <br> <script> document.write("Image name: "); document.write(document.getElementById('compman').name); </script> </body> </html>

補充一點實務經驗:在 HTML5 中,img 的 name 屬性已不屬於標準定義,因此不同瀏覽器讀出來的結果未必一致。若目的是「標記這張圖給程式辨識」,建議改用 id 或自訂的 data-* 屬性,再透過 dataset 讀取,這樣語意清楚也更穩定。

希望本文所述對大家的 JavaScript 程式設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved