简体   繁体   English

你如何得到一个变异观察者来检测textarea的值变化?

[英]How do you get a mutation observer to detect a value change of a textarea?

I have seen mutation observers used to obtain the properties of doms when they are modified such as with the google chrome developer tools. 我已经看到变异观察者用它来修改doms的属性,例如使用谷歌浏览器开发工具。 I can't, however, find how to call a function when the text within a textarea changes due to a user typing or pasting. 但是,当textarea因用户输入或粘贴而发生更改时,我无法找到如何调用函数。 In my code, as the user types the callbacks don't get called, even with all the observe options set to true. 在我的代码中,当用户键入时,即使将所有observe选项设置为true,也不会调用回调。 What is the code for this? 这是什么代码?

The mutation observers listen for changes of the DOM. 突变观察者监听DOM的变化。 The current state of form elements, however, is not reflected by the DOM. 然而,表单元素的当前状态不会被DOM反映出来。

For example, create an input element input without setting the value attribute. 例如,在不设置value属性的情况下创建输入元素输入 When text is being entered into the input field, input.value reflects this text. 当文本输入到输入字段时, input.value会反映此文本。 On the other hand, input.getAttribute('value') still returns null . 另一方面, input.getAttribute('value')仍然返回null

Therefore, the mutation observers can't observe this change in the form field's status. 因此,变异观察者无法在形式字段的状态中观察到这种变化。

(Object.observe of the proposed ECMAScript 6th edition also doesn't help. Although one can listen on changes of host objects in recent versions of Chrome, changes of host object properties like value of input above are not being observed.) (提议的ECMAScript第6版的Object.observe也没有帮助。虽然可以在最近版本的Chrome中监听主机对象的更改,但是没有观察到主机对象属性的更改,例如上面输入的 。)

See this link Textarea onchange detection . 查看此链接Textarea onchange detection You will need to write onkeyup and onchange function. 您需要编写onkeyup和onchange函数。

By the way, the answer above will not work for an input method. 顺便说一句,上面的答案不适用于输入法。 My solution is setInterval to detect if the text has changed every 50 ms. 我的解决方案是setInterval来检测文本是否每50毫秒更改一次。

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

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