简体   繁体   中英

javascript: call function by classname

Trying to create a script that is bound by className and calls another function.

I have this code working for first instance of className, but if I remove the [0] in the first line of the script it no longer works.

  <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>

How do I get it to work for all inputs with className="Bound" ? I do not need a jQuery solution.

Thank you.

Use a loop to iterate all elements.

Use Array#forEach , forEach() method executes a provided function once per array element.

Another alternate could to use Array.from over HTMLCollection returned by getElementsByClassName so that you can invoke Array# methods directly over returned result.

 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" /> 

Notes:

Iterate over NodeList and attach event handler to the element.

 // 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" /> 

simply iterate all the Node (s) in a NodeList (with a good old for-loop :))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM