简体   繁体   中英

Javascript for loop not working on function keydown

In my code for alert all the lines of textarea filed on every keydown event but loop not working

function limitTextareaLine(e) {

  var textArray = $(this).val().split("\n");
  for(var v in textArray){ // Only iterate first line
    alert(textArray[v] +" "+textArray.length); 
  }

}

$(function() {
    $('textarea.limited').keydown(limitTextareaLine);
});

In Javascript you need to loop through the array using numbers, you were using the values in the array. You need the following:

function limitTextareaLine(e) {

  var textArray = $(this).val().split("\n");
  for(v=0; v < textArray.length; v++){
    alert(textArray[v] +" "+textArray.length); 
  }

}

$(function() {
    $('textarea.limited').keyup(limitTextareaLine);
});

I've also changed the event to keyup so that it triggers the event after the key has been recorded in the box.

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