是否有一种方法可以跟踪对HTML元素的所有更改

Is there a way to track all change to an HTML element?

本文关键字:元素 HTML 跟踪 一种 是否 方法      更新时间:2023-09-26

是否有一种(好的)方法来跟踪HTML元素的所有更改?

我尝试使用javascript与jQuery,但它不工作。

$('div.formSubmitButton input[type="submit"]').change(function(event){
                alert(event);
            });

在提交按钮上设置了一个样式属性,但我找不到它是在哪里以及如何完成的。

编辑:我的问题不是jQuery特有的

您可以使用mutationobserver:

跟踪对DOM元素所做的更改。
// select the target node
var target = document.querySelector('div.formSubmitButton input[type="submit"]');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation);
    });    
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true }
// pass in the target node, as well as the observer options
observer.observe(target, config);
http://jsfiddle.net/2VwLa/

这将为您提供一个MutationRecord对象,其中包含更改内容的详细信息。更多关于突变的信息请访问:https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/

您可以跟踪输入字段的更改或检查提交:

  $('form').submit(function(event){
     alert("this gets called when form submitted here you can test differences");
  });

  $('form input[type="text"]').change(function(event){
     alert("this gets called when and text input field gets changed");
  });

更进一步,你可以检查特定输入字段的键盘输入:

  $('form input[type="text"]').keydown(function(event){
     alert("this gets called on key board input before the data is inserted in input field");
  });
  $('form input[type="text"]').keyup(function(event){
     alert("this gets called on key board input after the data is inserted in input field");
  });

注意:type="text"只是一个示例,您可能还希望包含您的密码和电子邮件字段。