替换onkeydown属性html和javascript

时间:2017-03-21 01:18:37

标签: javascript html

我试图做一个你输入文字的东西,按回车,运行functionOne,然后当你再次按回车时它会运行functionTwo。

<input type="text" onKeyDown="if(event.keyCode==13) myFunction()" id="theText" name="reverseMe" value=""><br>

那是我的文本框

document.getElementsByName("theText")[0].onKeyDown = "if(event.keyCode==13) functionTwo()";

在functionOne的末尾 问题是,当我按Enter键时,它仍会运行functionOne。

2 个答案:

答案 0 :(得分:0)

这些方面的东西。无需存储全局变量。请注意HTML中的data-call-count字段和JavaScript中的input.dataset.callCount

function myFunction(input) {
  var callCount = Number(input.dataset.callCount) + 1
  input.dataset.callCount = callCount
  if(callCount === 1) functionOne()
  else if(callCount === 2) functionTwo()
  else console.log('Call ', callCount)
}

function functionOne() {
  console.log("I'm function one!")
}

function functionTwo() {
  console.log("I'm function two!")
}
<input type="text" onKeyDown="if(event.keyCode==13) myFunction(this)" id="theText" name="reverseMe" value="" data-call-count="0">

答案 1 :(得分:0)

您可以将属性存储到textarea以保存迭代次数,例如:

function handleKeyDown (event) {
  var textarea = event.target;
  var iterations = textarea.getAttribute('data-iterations') || 0;
  if (+iterations <= 1) {
    callFunctionOne();
    textarea.setAttribute('data-iterations', +iterations + 1);
  } else {
    callFunctionTwo();
    textarea.setAttribute('data-iterations', 0);
  }
}

// Then add the event listener to your textarea
document.getElementsByName("theText")[0].addEventListener('keydown', handleKeyDown);

这样,每当您尝试与textarea进行交互时,代码将首先检查之前是否存在迭代。如果是,代码将调用您的第二个函数并重置迭代计数。下次调用它时,将再次调用第一个函数。

这也很有用,因为只需检查其data-iterations属性,您就可以轻松地从其他功能中获取复选框的状态。