我不能改变任何样式属性边框,颜色等,为什么?我总是得到:
未捕获TypeError: can't access property "color", icon。样式未定义
<!-- this element is created multipleTimes by loop -->
<li class="list-group-item">
<span>
<input class="input_Text" data-verb="<%= data %>" type="text">
<i class="fas fa-check checkIcon" ></i>
</span>
</li>
let check = document.querySelectorAll('.input_Text')
/* */
var icon = document.querySelectorAll('.checkIcon');
check.forEach(element => element.addEventListener('input',(e)=>{
var data = element.getAttribute('data-verb').toString();
var value = e.target.value;
if (value == ""){
element.style.border = "1px solid blue";
element.style.color = "black";
}
else if (data.startsWith(value)){
element.style.border = "5px solid green";
element.style.color = "green";
}
else{
element.style.border = "5px solid red";
element.style.color = "red";
}
<!-- HERE -->
value == data?icon.style.color = "green" : null;
}));
这是由于icon
querySelectorAll不是元素本身(参见下面如何返回单个元素)。
返回一个NodeList,它非常类似于Array。要执行所需操作,需要获得该列表返回的第一个节点。有一些方法可以做到这一点:
// Deconstructing it as an array, I'm not sure if you can really do this with a NodeList, should be tested
var [icon] = document.querySelectorAll('.checkIcon');
// Get item x where x is the index (in your case, 0, the first element)
var icon = document.querySelectorAll('.checkIcon').item(0);
// This is valid syntax, same as .item()
var icon = document.querySelectorAll('.checkIcon')[0];
获取单个元素本身
或者,正如在回答注释中所指出的,您可以使用文档.querySelector()
API
引用:
- 节点列表的.item ()
- 文档的.querySelectorAll ()