如何用按钮修改“ oninput”?

时间:2019-02-28 18:25:38

标签: javascript html attributes element

如果表中已经有oninput = "insertScriptHere,insertScript2Here",将oninput = "insertScriptHere添加到数据表的最佳方法是什么?我只希望在按下按钮后将第二个脚本加入oninput。

要重申:我有<input type="number" placeholder="-" size="2" maxlength="3" id="s1g1" oninput="constraint(this)"> 并且我希望在单击按钮后将其更改为<input type="number" placeholder="-" size="2" maxlength="3" id="s1g1" oninput="constraint(this),autoEnable()">

按钮:<button id="calcGrades" onclick="calcGrades(),autoEnable()">Calculate Final Grades</button>

到目前为止,我已经尝试过:document.getElementById("s1g1").setAttribute("oninput","script1(),script2()"); document.getElementById("s1g2").element('onInput()','script1(),script2()');

,但都没有奏效。我正在使用一个按钮来激活以上功能。我不确定实际上称为“ oninput”(属性?元素?)。

答案:我通过使用以下语法对其进行了修复:

var s1g1 = document.getElementById("s1g1"); s1g1.setAttribute("oninput","calcGrades(),constraint()")

激活时将同时设置calcGrades()和Constraint()!

1 个答案:

答案 0 :(得分:0)

首先不要使用oninput。使用.addEventListener()

// Get references to elements:
let input = document.getElementById("s1g1");
let btn = document.getElementById("calcGrades");

// Set up event handlers:
input.addEventListener("input", constraint); 
btn.addEventListener("click", function(){
  calcGrades();
  autoEnable();
});

// "Flag" to know if the button has been clicked before
let notClicked = true;

function constraint(){
  // Do whatever this function does
  console.log("function constraint invoked.");
  
  // Check to see if the button has not been clicked before
  if(notClicked){
    // Add a second event handler
    input.addEventListener("input", autoEnable);
    notClicked = false; // set flag so this won't happen again
  }
}

function calcGrades(){ console.log("function calcGrades invoked."); }
function autoEnable(){ console.log("function autoEnable invoked."); }
<!-- See how much cleaner the HTML is when we don't do event binding here? -->
<input type="number" placeholder="-" size="2" maxlength="3" id="s1g1">
<button id="calcGrades">Calculate Final Grades</button>