如何防止我的if语句第一次运行?

时间:2015-05-14 21:00:50

标签: javascript

快速问题,因为我正在绘制一个空白,如果我有一个事件监听器,其中包含2个if语句,这些语句在第一轮时都是正确但我不希望它们都执行我是如何执行的防止这个?我可以打破第一个条件或类似的东西吗?

JS

var input = document.querySelector('.js-input'),
    output = document.querySelector('.js-output');

input.addEventListener('keydown', function (event) {
    if (this.value.length === 0) {
        console.log('run this once');
    }

    if (this.value === '') {
        console.log('this is empty so show hint')
    }
});

3 个答案:

答案 0 :(得分:1)

var input = document.querySelector('.js-input'),
    output = document.querySelector('.js-output');
var firstTimeCallbackRun= true;

input.addEventListener('keydown', function (event) {
    if (this.value.length === 0) {
        console.log('run this once');
        if(firstTimeCallbackRun) {
          firstTimeCallbackRun = false;
          return;
        }
    }

    if (this.value === '') {
        console.log('this is empty so show hint')
    }
});

答案 1 :(得分:0)

var input = document.querySelector('.js-input'),
    output = document.querySelector('.js-output'),
    isFirst = true;

input.addEventListener('keydown', function (event) {
    if (isFirst) {
      isFirst = false;
      return;
    }
    if (this.value.length === 0) {
        console.log('run this once');
    }

    if (this.value === '') {
        console.log('this is empty so show hint')
    }
});

答案 2 :(得分:0)

也许是这样的?但是你应该问问自己为什么会这样,你做错了什么。因为这是一个hacky而非最佳的解决方案。

(function() {
    var firstRun = true;

    var input = document.querySelector('.js-input');
    var output = document.querySelector('.js-output');

    input.addEventListener('keydown', function (event) {
        if (firstRun) {
            firstRun = false;

            if (this.value.length === 0) {
                console.log('run this once');
            }
        } else {
            if (this.value === '') {
                console.log('this is empty so show hint')
            }
        }
    });
})();

这里有example如何实现这一目标:

(function() {
  var input = document.querySelector('.js-input');

  var isDirty = function(element) {
    if ( ! element.data) {
        element.data = {isDirty: false};
    }

    if (element.value.length > 0 && ! element.data.isDirty) {
        element.data.isDirty = true;
    } else if (element.value.length === 0) {
        element.data.isDirty = false;
    }

    return element.data.isDirty;
  };

  input.addEventListener('keyup', function (event) {
    var dirtyClass = " is-dirty";

    if (isDirty(this)) {
      if (this.className.search(dirtyClass) === -1) {
        this.className += dirtyClass; 
      }
    } else {
      this.className = this.className.replace(dirtyClass, "");
    }
  });
})();