小唯快跑啊
2023-06-15 16:48:30
<input name='x' id='y' list='z'>在 JavaScript 中,你可以這樣做var input = document.createElement('INPUT');input.id = 'x'; //this worksinput.name = 'y'; //this also worksinput.list = 'z'; //this does not work我的問題很簡單:這里發生了什么魔法?為什么 .id 和 .name 有效,但 .list 無效(需要使用 setAttribute 設置) ?有沒有辦法知道(除了知道一切)在輸入元素上設置列表屬性的方法正在使用setAttribute("list", "z");?setAttribute 調用的魔力是什么,而 input.list 不是?
2 回答

LEATH
TA貢獻1936條經驗 獲得超7個贊
這不起作用,因為list
an 的屬性HTMLInputElement
被定義為只讀
interface?HTMLInputElement?:?HTMLElement?{? ?[HTMLConstructor]?constructor(); ??... ??readonly?attribute?HTMLElement??list;??? ??... ?? }

交互式愛情
TA貢獻1712條經驗 獲得超3個贊
這里的問題是像id
和這樣的屬性name
可以追溯到文檔對象模型 (DOM)的更舊版本——可以追溯到1990 年代中期的DOM 級別 0(或“舊版 DOM” )。這些 DOM 屬性與 HTML 標記中的同名屬性完全對應。
相比之下,將元素list
的預定義內容附加<datalist>
到<input>
元素的屬性要晚得多。它在 2018-19 年左右開始出現在大多數瀏覽器中。
(即使是現在,CanIUse 也表明它在 Firefox 中還沒有準備好......盡管我自己在Firefox 83中的實驗表明它已經準備好了。)
因此,最可靠的方法是使用:
const myInput = document.createElement('input');
myInput.setAttribute('id', 'x');
myInput.setAttribute('name', 'y');
myInput.setAttribute('list', 'z');
console.log(myInput.getAttribute('id'));
console.log(myInput.getAttribute('name'));
console.log(myInput.getAttribute('list'));
添加回答
舉報
0/150
提交
取消