JS A simple way to dynamically add events to objects
- 2021-07-04 17:56:26
- OfStack
In WEB projects, we often encounter the need to dynamically add events to the corresponding objects, such as the text box control with id= "txtPrice":
<div>
<input type="text" id="txtPrice" name = "txtPrice" value = "0"/>
<div>
Now let's dynamically add 1 event to it. The core code of JS is as follows:
document.getElementById("txtPrice").attachEvent('onblur', function (){alert(' Add event successfully! ')});
[Supplement]
Sometimes in order to achieve compatibility between different browsers, we will write this:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->1 if(window.attachEvent)
{
document.getElementById("txtPrice").attachEvent('onblur', function (){alert(' Add event successfully! ')});
}
else
{
document.getElementById("txtPrice").addEventListener('onblur', function (){alert(' Add event successfully! ')} , false);
}