占位符宽度函数抛出Uncaught TypeError: Cannot read property 'lengt

Placeholder width function throws Uncaught TypeError: Cannot read property 'length' of null

本文关键字:property read Cannot lengt TypeError 函数 Uncaught 占位符      更新时间:2023-09-26

我是Js的新手,我不能确定错误的来源:

我正在使用一个函数来自动调整输入字段的大小到占位符的大小;代码工作得很好afaik但是开发工具告诉我"不能读取null属性'length' "

我有点迷失在这一点上:我试图改变数据(JSON)的类型没有成功,检查是否有与元素ID相关的东西;我已经看过一些类似的问题,但还没能找出问题的症结。

这是一段实际代码

var input = document.querySelectorAll('input');
for(i=0; i<input.length; i++){
   input[i].setAttribute('size',input[i].getAttribute('placeholder').length);
}

radio按钮没有占位符,所以getAttribute('placeholder')返回null

你需要调整你的选择器,只抓取input[type='text'](或超级安全,input[placeholder])。