简体   繁体   English

jQuery .on(“ change”)运行越来越多,但我只希望它运行一次

[英]jQuery .on(“change”) running more and more times but I only want it to run once

I'm trying to detect changes to input text fields. 我正在尝试检测输入文本字段的更改。 Whenever the user changes something in an input I want to grab the new value and validate it. 每当用户更改输入中的某些内容时,我都希望获取新值并进行验证。 My problem is that the code I'm using appears to be running more and more each time. 我的问题是我正在使用的代码似乎每次都越来越多地运行。 It will detect a change to an input once. 它将一次检测到输入的更改。 But then the next time one input is changed, the code will run twice. 但是,下次更改一个输入时,代码将运行两次。 Then three times, four times, and so on. 然后三遍,四遍,依此类推。 What is it that I'm doing wrong? 我做错了什么事?

Here is my HTML: 这是我的HTML:

<div class="input-wrapper">
  <input name="clickthru1" type="text" value="input1">
  <input name="clickthru2" type="text" value="input2">
  <input name="clickthru3" type="text" value="input3">
</div>

And here is my jQuery: 这是我的jQuery:

$( ".input-wrapper" ).on( "focus", "input", function() {

  console.log("focus on input detected");

    $( ".input-wrapper" ).on( "change", "input", function() {
      console.log("change to value detected");
    });

});

And here is a link to the codepen: http://codepen.io/jimmykup/pen/yYvbzK 这是指向代码笔的链接: http ://codepen.io/jimmykup/pen/yYvbzK

Move change event assignment outside of focus event: change事件分配移至focus事件之外:

$( ".input-wrapper" ).on( "focus", "input", function() {
  console.log("focus on input detected");
});

$( ".input-wrapper" ).on( "change", "input", function() {
  console.log("change to value detected");
});

That is because you add 'on change' function to stack each time focus event is fired. 这是因为您添加了“ on change”功能来在每次触发焦点事件时进行堆栈。 So just put it out of focus functionality. 因此,只需将其移出焦点功能即可。

$( ".input-wrapper" ).on( "focus", "input", function() {
  console.log("focus on input detected");
});

$( ".input-wrapper" ).on( "change", "input", function() {
  console.log("change to value detected");
});

Everytime you focus on the input, a new change event handler is added to it. 每当您专注于输入时,都会向其添加新的更改事件处理程序。 So the first time you focus, you will get one console log, the second time you focus you will get 2 , then 3 and so on. 因此,第一次专注时,您将获得一个控制台日志,第二次专注时,您将获得2,​​然后是3,依此类推。

The solution is to remove the nesting you currently have to only have one function call for each type of event: 解决方案是删除每种类型的事件当前只需要一个函数调用的嵌套:

$( ".input-wrapper" ).on( "focus", "input", function() {
  console.log("focus on input detected");
});

$( ".input-wrapper" ).on( "change", "input", function() {
   console.log("change to value detected");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM