javascript获取和使用输入值

时间:2018-09-26 14:45:55

标签: javascript

你好,我只是想知道是否有获得输入值的更改/将其用于healLevel = 70%我尝试了一下,但是我对此并不陌生。

(function() {
  var checkbox1 = document.getElementById("cb1");
  var checkbox2 = document.getElementById("cb2");

  heal = document.getElementsByClassName('hud-shop-item')[10];
  petHeal = document.getElementsByClassName('hud-shop-item')[11];
  useHeal = document.getElementsByClassName('hud-toolbar-item')[4];
  usePetHeal = document.getElementsByClassName('hud-toolbar-item')[5];
  healthBar = document.getElementsByClassName('hud-health-bar-inner')[0];
  up = new Event('mouseup');
  healLevel = 70;

  HEAL1 = function() {
    if (checkbox1.checked) {
      heal.attributes.class.value = 'hud-shop-item';
      useHeal.dispatchEvent(up);
      heal.click();
    }
  };

  HEAL2 = function() {
    if (checkbox2.checked) {
      petHeal.attributes.class.value = 'hud-shop-item';
      usePetHeal.dispatchEvent(up);
      petHeal.click();
    }
  };

  script = function(e) {
    if (e.keyCode == 82) {
      HEAL1();
      HEAL2();
    }
  };
  document.addEventListener('keydown', function(e) {
    script(e);
  });
  observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
      if (parseInt(mutations[0].target.style.width) < healLevel) {
        HEAL1();
        HEAL2();
      }
    });
  });
  observer.observe(healthBar, {
    attributes: true,
    attributeFilter: ['style']
  });
})();
<input type="number" min="1" max="100" value="70">

这就是我尝试过的方法,但是没有发现为什么我失败的任何想法? 我尝试使用document.querySelector我在做什么错了?

(function() {
  var checkbox1 = document.getElementById("cb1");
  var checkbox2 = document.getElementById("cb2");
  var elem = document.querySelector('input[type="number"]');

  heal = document.getElementsByClassName('hud-shop-item')[10];
  petHeal = document.getElementsByClassName('hud-shop-item')[11];
  useHeal = document.getElementsByClassName('hud-toolbar-item')[4];
  usePetHeal = document.getElementsByClassName('hud-toolbar-item')[5];
  healthBar = document.getElementsByClassName('hud-health-bar-inner')[0];
  up = new Event('mouseup');
  healLevel = elem.value;

 
<input type="number" min="1" max="100" value="70">

1 个答案:

答案 0 :(得分:1)

HTML

<input type="number" min="1" max="100" value="70" id="healRate" onchange="updateHealLevel()">

JS

var healLevel = document.getElementById("healRate").value;

function updateHealLevel(){
healLevel = document.getElementById("healRate").value;
}

编辑

已更新,以便更改输入值将更新healLevel。

要在输入中更改值,您只需在HTML组件上添加一个onchange事件,以便在用户更改此输入时,它将运行将更新healLevel的代码。