如何运行脚本两次



我在同一页上有两个相同的表单,并且脚本只适用于第一个表单。我是一个初学者,这对我来说是一个挑战;我尝试添加`for(var I=0;I<input.length;I++(,但没有成功。如果有任何帮助,我将不胜感激。

var el = document.querySelector(".js-tac");
input = document.querySelector('.js-tel')
input.addEventListener('input', evt => {
const value = input.value
if (!value) {
el.classList.remove("is-visible");
return
}
const trimmed = value.trim()
if (trimmed) {
el.classList.add("is-visible");
} else {
el.classList.remove("is-visible");
}
})

document.querySelector返回第一个匹配的元素。所以你需要document.querySelectorAll,它会给出一个集合。然后像这个一样迭代这个集合

document.querySelectorAll('.js-tel').forEach((input)=>{
// not using arrow function since using this to target the element
input.addEventListener('input', function(evt){
const value = this.value
// rest of the code
})
})

问题是您只得到一个输入元素。(querySelector返回第一个匹配元素,而不是所有匹配元素(。您可能希望使用querySelectorAll来获取NodeList(其中包含所有匹配的节点(。您可以对其进行迭代。

根据您使用它的方式,我建议您确保js-tacjs-tel封装在一些常见的父级中,并使用querySelectorAll来查找它们。然后,您可以使用querySelector来查找js-teljs-tac

var nodes = document.querySelectorAll('.js-parent')
//If you don't export forEach to be available, you can also just do a standard
//for loop here instead.
nodes.forEach((parent) => {
var el = parent.querySelector(".js-tac");
input = parent.querySelector('.js-tel')
...
})

最新更新