2013-05-14 122 views
4

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

我试图用JavaScript与jQuery,但它不起作用。

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

不知何故style属性设置在提交按钮上,但我找不到在哪里以及如何完成。

+2

查看浏览器的文档检查器? – George 2013-05-14 09:38:36

+2

如何“更改”提交按钮? – adeneo 2013-05-14 09:40:11

+0

我想拦截变化(由js触发),看看它是否被改变@adeneo,当你做$ SubmitInput.addClass('this')会发生什么? ? – maazza 2013-05-14 09:44:46

回答

5

您可以通过使用mutationobservers跟踪做一个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/

+1

正是我想要的 – maazza 2013-05-15 11:12:40

+1

不要忘记取消注册你的观察员,一旦你得到你需要的东西。我知道它是一件棘手的事情。 – Mircea 2013-06-01 00:06:14

+0

有没有办法为IE9填充MutationObserver?它似乎还没有出现在IE中。 – Doug 2013-11-06 03:08:25

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"是只有一个例子,你可能也希望你的密码和电子邮件字段包含在内。 (和选择框,如果你使用变化事件)

+0

我声明我使用的是一个提交按钮,它并不是被更改的值,而是元素本身的属性 – maazza 2013-05-14 09:46:50

+0

这些值只能由例如chrome中的javascript/jquery或元素检查器来更改。你无法捕捉到这些变化..如果你创建了一个事件监听器,并且在每次更改后都调用它,那么你可以捕获自己的更改。或者你在提交时检查差异。 – 2013-05-14 09:51:39

+0

错误的joel你可以:D – 2013-05-14 09:54:12

相关问题