作爲一個例子(請關注問題,而不是例子 - 我有很好的理由),我試圖在Javascript中的HTMLSelectElement對象上添加一個新的'placeholder'屬性。所以我是這樣的:如何在Javascript中有效地定義HTMLElement屬性以便能夠使用HTML進行設置?
<select id="gender" name="gender" placeholder="Male">
<option></option>
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
現在,如果我跑,我得到 '未定義':
var gender = document.getElementById('gender');
alert(gender['placeholder']);
所以嘗試過這種方法,看看這是否會幫助:
HTMLSelectElement.prototype.placeholder = '';
但現在我得到一個空字符串。有沒有一種簡單的方法來訪問HTMLElements上的自定義屬性,而不必逐一循環遍歷HTMLElement.attributes?請記住,我使用的是Vanilla JS和一些舊瀏覽器。
使用'.placeholder'設置/獲取佔位符'alert(gender.placeholder);' – www139
select沒有佔位符......那麼試圖解決什麼? – epascarello
@epascarello正是我想添加一個佔位符屬性來選擇元素。 –