dav*_*vid 0 javascript function getelementsbyclassname
尝试创建一个由className绑定的脚本并调用另一个函数.
我有这个代码工作的第一个className实例,但如果我删除[0]脚本的第一行它不再有效.
<input type="text" value="NOTBound" class="NOTBound"/>
<input type="text" value="Bound value 1" class="Bound"/>
<input type="text" value="NOTBound" class="NOTBound"/>
<input type="text" value="Bound value 2" class="Bound"/>
<script>
inputBound = document.getElementsByClassName('Bound')[0];
inputBound.onfocus = function() {
var input = this.value;
formFunct(input);
}
function formFunct(input) {
console.log('done did the form Funct: ' + input)
}
</script>
Run Code Online (Sandbox Code Playgroud)
如何让它适用于所有输入className="Bound"?我不需要jQuery解决方案.
谢谢.
使用循环迭代所有元素.
使用Array#forEach,forEach()方法每个数组元素执行一次提供的函数.
另一个替换可能使用Array.from了HTMLCollection由返回getElementsByClassName,这样就可以调用Array#方法直接在返回的结果.
var inputBound = document.getElementsByClassName('Bound');
[].forEach.call(inputBound, function(inputBound) {
inputBound.onfocus = function() {
var input = this.value;
formFunct(input);
}
})
function formFunct(input) {
console.log('done did the form Funct: ' + input)
}Run Code Online (Sandbox Code Playgroud)
<input type="text" value="NOTBound" class="NOTBound" />
<input type="text" value="Bound value 1" class="Bound" />
<input type="text" value="NOTBound" class="NOTBound" />
<input type="text" value="Bound value 2" class="Bound" />Run Code Online (Sandbox Code Playgroud)
笔记:
[].forEach.call.for-loop迭代
HTMLCollection.