简体   繁体   中英

Jquery - increment global variable

I have the following nicEditor implementation and am trying to change a behavior once I set var over = 1. Here is the desired behavior:

  1. Until text length = 5, we get the console message: "under 5, first go"
  2. As the text length continues to increase over 5, we get the message: "over 5"
  3. If we then reduce the text length back below 5, we get the message: "YAYYYYY, I got it!"

Right now, if the text length goes back below 5, we go back to the "under 5, first go" message. I think the solution is to change the value of var over as a global variable but cannot figure out how to do this. . Here is the jsfiddle: http://jsfiddle.net/jGLRn/182

HTML

JS: nicEditors.allTextAreas();

var over = 0;
$("div.nicEdit-main").keyup(function() {
  var text_count = $(this).text().length;
  if ($(this).text().length < 5) {
    var text = $(this).text();
    $('#id_desc').val(text);
    console.log("under 5, first go");
  } else {
    var text = $(this).text();
    $('#id_desc').val(text);
    console.log("over 5");
    $('.nicEdit-main').removeClass('error');
    $("#id_desc-error").remove();
    over = 1;
  }

  if ((over == 1) && (text < 5)) {
    console.log("YAYYYYY, I got it!");
  }
});

You are creating a shadow-variable over , since you do var over in your keyup function, which means inside of keyup, over will always reference the non-global one. Remove that line and it will work

Remove var over; from keyup handler as your handle is using this as a variable and not incrementing the global one.

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