2016-02-12 44 views
0

如何監視何時爲對象分配了onclick特性? 我想在處理程序分配時通知。如何監視何時在對象上分配onclick屬性javascript

<input type="text" id="test"> 

<script> 
var testObj = document.getElementById('test'); 
console.log(testObj.onclick); // return null 

testObj.onclick = function() { // assign handler 
    console.log("Clicked !!"); 
} 

console.log(testObj.onclick); // return function 
</script> 

回答

0

嘗試使用:

testObj.addEventListener("click",function() { 
    console.log("Clicked !!"); 
}); 

這裏是例子: https://jsbin.com/sewuyuyahu/edit?html,output

+0

您的代碼使用'addEventListener'函數。但是我們的問題是當我們將屬性賦值給一個對象時監視。 –

+0

因此改變這個 console.log(testObj.onclick); for this: console.log(testObj.onclick()); –

+0

我認爲OP正試圖詢問如何分辨處理程序是否已分配。或者如何在處理程序分配時得到通知。這有點不清楚,但不問如何分配處理程序。 – nnnnnn

0

嘗試mutationObserver

var target = document.getElementById('test'); 

// create an observer instance 
var observer = new MutationObserver(function(mutations) { 
    mutations.forEach(function(mutation) { 
    if (mutation.type == "attributes" && mutation.attributeName == "onclick") 
    { 
     console.log("onclick assigned"); 
    } 
    });  
}); 

// configuration of the observer: 
var config = { attributes: true }; 

// pass in the target node, as well as the observer options 
observer.observe(target, config); 
+0

謝謝,但它不起作用。 –

0

我不認爲這是一個事件,JavaScript的火災時呼叫addEventListenerelement.onlcik

作爲一個骯髒的解決方法,您可以調用一個附加的自己的函數來通知/監視添加的事件。

//Example 

registerEvent(obj, eventname) { 
    //save this for monitoring purpose. 
} 

//Notify here... 
registerEvent(testObjet, 'onclick'); 
testObj.onclick = function() { // assign handler 
    console.log("Clicked !!"); 
} 
相關問題