4

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

我尝试将 javascript 与 jQuery 一起使用,但它不起作用。

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

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

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

4

2 回答 2

6

您可以使用突变观察者跟踪对 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/

于 2013-05-15T10:49:55.463 回答
0

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

  $('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"这只是一个示例,您可能还希望包含您的密码和电子邮件字段。(如果您在更改事件中使用,请选择框)

于 2013-05-14T09:44:28.823 回答