gpt4 book ai didi

javascript - 如果使用类名填充,则更改输入样式

转载 作者:行者123 更新时间:2023-11-30 09:59:37 26 4
gpt4 key购买 nike

我发现 fiddle 可以在填充时更改输入样式。但它正在使用ID。我想使用类名。我用了document.getElementsByClassName() ,但它不起作用。任何人都可以帮忙吗?谢谢。

这是代码

html

<input type="text" id="subEmail" onchange="checkFilled();"/>

Javascript

function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
else{
inputVal.style.backgroundColor = "";
}
}

checkFilled();

这里是 Fiddle 的链接

最佳答案

getElementsByClassName() 返回 dom 元素数组,因此您需要使用 inputVal[0] 代替 inputVal

function checkFilled() {
var inputVal = document.getElementsByClassName("subEmail");
if (inputVal[0].value == "") {
inputVal[0].style.backgroundColor = "yellow";
} else {
inputVal[0].style.backgroundColor = "";
}
}

checkFilled();
<input type="text" class="subEmail" onchange="checkFilled();" />

Document.getElementsByClassName() : Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

取自: here

关于javascript - 如果使用类名填充,则更改输入样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32371701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com