javascript: 按类名调用函数

javascript: call function by classname

正在尝试创建一个由 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>

如何让它适用于 className="Bound" 的所有输入?我不需要 jQuery 解决方案。

谢谢。

Use a loop to iterate all elements.

使用Array#forEachforEach()方法对每个数组元素执行一次提供的函数。

另一个替代方案可以使用 Array.from 而不是 getElementsByClassName 返回的 HTMLCollection,这样您就可以直接在返回的结果上调用 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)
}
<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" />

备注:

遍历 NodeList 并将事件处理程序附加到元素。

// get all elements and convert to array
Array.from(document.getElementsByClassName('Bound'))
  // iterate overa array elements
  .forEach(function(ele) {
    // bind event handler
    ele.onfocus = function() {
      var input = this.value;
      formFunct(input);
    }
  });

function formFunct(input) {
  console.log('done did the form Funct: ' + input)
}
<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" />

简单地迭代 NodeList 中的所有 Node(s)(使用一个很好的旧 for 循环 :))

inputBounds = document.getElementsByClassName('Bound');
for( var counter = 0; counter < inputBounds.length; inputBounds++ )
{
  inputBounds.item( counter ).onfocus = function() {
      var input = this.value;
      formFunct(input);
  }   
}