2016-02-12 57 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 !!"); 
}