没有匿名函数的eventlistener

时间:2018-01-10 15:35:29

标签: javascript scope addeventlistener

尝试使用纯JavaScript查找文本框中的文本长度。为什么这是一个冗长的方法:



var first_name = document.getElementById("firstname");
first_name.addEventListener("change", howLong(first_name));

function howLong(first_name) {
  var p = first_name.value.length;
  alert("Length of input is " + p);
}

<form>
  <input id="firstname" type="text" />
  <input type="submit" /> </form>
&#13;
&#13;
&#13;

不允许访问值(总是为零),而使用匿名函数

&#13;
&#13;
var first_name = document.getElementById("firstname");
  first_name.addEventListener("change", function(){
		var p = first_name.value.length;
		alert("Length of input is "+p);
  } );
&#13;
<form>
<input id="firstname" type="text"/>
<input type="submit"/> </form>
&#13;
&#13;
&#13;

工作正常吗?

3 个答案:

答案 0 :(得分:2)

你想要你自己传递函数howLong而不是调用函数并传递结果。工作代码:

&#13;
&#13;
var first_name = document.getElementById("firstname");
first_name.addEventListener("change", howLong); // instead of howLong(first_name)

function howLong() {
  var p = first_name.value.length;
  alert("Length of input is " + p);
}
&#13;
<form>
  <input id="firstname" type="text" />
  <input type="submit" /> </form>
&#13;
&#13;
&#13;

正如@Andreas所说,最好在函数中使用this而不依赖于全局变量,因为这会给你更好的灵活性(例如你可以将同样的函数用于其他输入):

&#13;
&#13;
var first_name = document.getElementById("firstname");
first_name.addEventListener("change", howLong); // instead of howLong(first_name)

function howLong() {
  
  var p = this.value.length;
  alert("Length of input is " + p);
}
&#13;
<form>
  <input id="firstname" type="text" />
  <input type="submit" /> </form>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您将howLong(first_name)的返回值传递给addEventListener而不是函数本身。一个可能的解决方案:

part 01       -match
part 33:      -match
part          -no match
participial   -no match

答案 2 :(得分:0)

在您的第一个示例中,howLong函数正在运行时执行,因此返回值0,因为尚未在input中输入任何内容。
你需要做的是传递函数本身:

&#13;
&#13;
var first_name = document.getElementById("firstname");
    first_name.addEventListener("change", () => howLong(first_name));

function howLong(first_name) {
  var p = first_name.value.length;
  alert("Length of input is " + p);
}
&#13;
<form>
  <input id="firstname" type="text" />
  <input type="submit" /> 
</form>
&#13;
&#13;
&#13;

相关问题