admin管理员组文章数量:1332339
I have Div element and Im setting its onClick event to null, like this.
child.onclick = null;
In this case child is a DOM element represent that DIV element.
Now the onclick
event is no longer there, and now I want to have it again like this.
child.onclick = new Function();
But that way does not work. I just want to have onclick
behavior as it was before it is set to null.
Can anyone help?
I have Div element and Im setting its onClick event to null, like this.
child.onclick = null;
In this case child is a DOM element represent that DIV element.
Now the onclick
event is no longer there, and now I want to have it again like this.
child.onclick = new Function();
But that way does not work. I just want to have onclick
behavior as it was before it is set to null.
Can anyone help?
Share Improve this question edited Jul 22, 2022 at 22:01 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 19, 2013 at 11:11 Dilan AlexDilan Alex 211 gold badge1 silver badge6 bronze badges 3-
1
Try
document.getElementById('myDiv').onclick= function(){//your code goes here};
– Harsha Venkataramu Commented Jun 19, 2013 at 11:13 -
If you are talking abour removing and attaching onclick functionality on the fly. Surely if you have a named function
function myFunc(){ //code here }
once you've setchild.onclick = null
you can re-attach the functionality you want withchild.onclick = myFunc;
?? – Mark Walters Commented Jun 19, 2013 at 11:15 - Once onClick is set to null we can still click on the DIV but nothing is happened. I just want to have the default behavior of onClick event. I do not have any function defined by me. – Dilan Alex Commented Jun 19, 2013 at 12:38
3 Answers
Reset to default 2// save reference to the old callback function
var oldOnclickFn = child.onclick;
// set onclick to null
child.onclick = null;
// set the onclick to the function that was there before.
child.onclick = oldOnclickFn;
However, you should probably look into addEventListener.
I would suggest using addEventListener
and removeEventListener
:
function handler(e){
}
to add listener:
child.addEventListener('click', handler);
to remove:
child.removeEventListener('click', handler);
NOTE as Mark Walters said, use attachEvent
and detachEvent
for IE < 9
Like this:
document.getElementById('clickme').onclick = function(){ alert('clicked'); };
http://jsfiddle/pJa9W/
本文标签: domAfter OnClick is set to null how do I have Onclick behavior again in JavaScriptStack Overflow
版权声明:本文标题:dom - After OnClick is set to null how do I have Onclick behavior again in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742329837a2454467.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论