[英]Can I track text change to an input field ONCE, not on every input?
I have a basic text input field and, for data analytics purposes, I want to track every time a user edits the text in that field as they edit it.我有一个基本的文本输入字段,出于数据分析的目的,我想在用户每次编辑该字段中的文本时对其进行跟踪。 I have this code so far:
到目前为止我有这个代码:
var input = document.querySelector("#inputId");
input.oninput = function (e) {
alert("changed");
}
The issue is that this fires every time the user deletes or adds a character, whereas I only want to know one single time that they are changing the text in the text field.问题是每次用户删除或添加字符时都会触发,而我只想知道他们正在更改文本字段中的文本一次。 Is there a way to achieve this?
有没有办法实现这一目标? I am new to jQuery and JavaScript so any direction would be really appreciated, thank you!
我是 jQuery 和 JavaScript 的新手,所以任何方向都将不胜感激,谢谢!
You can try using Parameters option once: true
:您可以尝试使用
once: true
参数选项once: true
:
once
: A Boolean indicating that the listener should be invoked at most once after being added.once
:一个布尔值,指示添加后最多应调用一次侦听器。 Iftrue
, the listener would be automatically removed when invoked.如果为
true
,则在调用时会自动删除侦听器。
Please Note: Internet Explorer yet to support this parameter characteristic.请注意: Internet Explorer 尚不支持此参数特性。
var input = document.querySelector("#inputId"); input.addEventListener('input', () => { alert("changed"); }, { once: true });
<input id="inputId"/>
If you only want the event handler to fire once per element, then you need to remove the event handler the first time it runs:如果您只希望事件处理程序为每个元素触发一次,那么您需要在第一次运行时删除事件处理程序:
var input = document.querySelector("#inputId");
input.addEventListener('input', yourFunc);
function yourFunc(e) {
alert("changed");
this.removeEventListener('input', yourFunc);
}
Note the use of addEventListener()
and removeEventListener()
instead of the outdated oninput
property.请注意使用
addEventListener()
和removeEventListener()
而不是过时的oninput
属性。
As you've tagged jQuery in the question you can also achieve it in this manner, using one()
:由于您在问题中标记了 jQuery,您也可以使用
one()
以这种方式实现它:
$('#inputId').one('input', function() {
alert('changed');
});
It sounds like you want to bind to the onchange
event instead: it is fired when the input value is "finalized" by the user, eg when he/she blurs from the field:听起来您想改为绑定到
onchange
事件:当用户“最终确定”输入值时,例如当他/她从字段中模糊时,它会被触发:
var input = document.querySelector("#inputId"); input.addEventListener('change', (e) => console.log('changed', e.target.value));
<input type="text" id="inputId" />
Just remove function when it call只需在调用时删除函数
let input = document.querySelector("#inputId"); input.oninput = function (e) { alert("changed"); input.oninput = undefined; }
<input id="inputId">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.