2013-05-14 96 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

相關問題