我被难住了,我发誓我一定错过了一些简单的东西,因为这对我来说没有任何意义。
展望未来,我希望从项目中删除jQuery,这似乎应该是最简单的任务,但对于我的生活,我无法弄清楚它。
我向一个似乎无法删除的元素添加了一个类。
注意:form-input被添加到标记中,而invalid是动态添加的
const telephoneInput = document.querySelector('#form-telephone');
console.log(telephoneInput.classList); // DOMTokenList [ "form-input", "invalid" ]
telephoneInput.classList.remove('invalid');
console.log(telephoneInput.classList); // DOMTokenList [ "form-input" ]从这里DOMTokenList/classList被更新,然而DOM没有更新,类和它的效果仍然存在。
上面运行后的DOM中的元素:<input name="form-telephone" id="form-telephone" class="form-input invalid" type="tel">
现在,如果我更改前面的测试,删除在原始标记form-input中添加的类,它将按预期工作……
const telephoneInput = document.querySelector('#form-telephone');
console.log(telephoneInput.classList); // DOMTokenList [ "form-input", "invalid" ]
telephoneInput.classList.remove('form-input');
console.log(telephoneInput.classList); // DOMTokenList [ "invalid" ]在此之后,DOMTokenList/classList再次被更新,这次DOM也被更新。
上面运行后的DOM中的元素:<input name="form-telephone" id="form-telephone" class="invalid" type="tel">
我是不是遗漏了什么,invalid类的添加是否改变了一些我没有意识到的东西?
发布于 2019-11-01 20:09:38
:invalid CSS伪类表示其内容无法验证的任何元素或其他元素。默认情况下,只要表单或输入无效,就会添加该类。您无法更改此行为。但是,您可以覆盖它:
input:invalid {
background-color: blue;
}这个伪类对于为用户突出显示字段错误很有用。
发布于 2019-11-01 20:10:49
<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
</style>
</head>
<body>
<p>Click the button to add the "mystyle" class to DIV.</p>
<button onclick="myFunction()">add</button>
<button onclick="myFunction1()">remove</button>
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and earlier versions.</p>
<div id="myDIV">
I am a DIV element
</div>
<script>
function myFunction() {
document.getElementById("myDIV").classList.add("mystyle");
}
function myFunction1() {
document.getElementById("myDIV").classList.remove("mystyle");
}
</script>
</body>
</html>
你可以在这里看到我的例子。我添加删除没有任何问题。所以这不是因为动态添加的类而导致的错误,这是"invalid“类的问题,它是表单字段的自动类。
建议:为您的目的使用不同的类
https://stackoverflow.com/questions/58658888
复制相似问题