How to assign an event to an object via DOM? Suppose I created
var tr = document.createElement('tr'); How do I assign the onclick event to the tr tag?
How to assign an event to an object via DOM? Suppose I created
var tr = document.createElement('tr'); How do I assign the onclick event to the tr tag?
tr.onclick = function(){ //do something } without setTimeout or window.onload, the script may not work in different browsers of different versions.
window.onload = fucntion(){ var tr = document.createElement('tr'); tr.onclick = function(){ //do something } } still as an option -
function myFunction () {
alert ("I was clicked");
}
var tr = document.createElement ("tr");
tr.onclick = myFunction;
PS: in JQuery, any event is usually described as element.event (function), but in the ECMAScript family of languages to which the JS belongs, the function is an object. This allows you to make a lot of all tastes, such as here, or even the dynamic construction of the function body. You can also, for example, write so that events are dynamically rewritten, for example:
element.onclick = myFunction;
function myFunction () {
// do something here
this.onclick = myAnotherFunction;
}
function myAnotherFunction () {
alert ("Now this function will be called when clicked");
}
Reply to comments:
The practical point is that you can "build" code in the execution process. The most primitive example is any switch. But as you understand, the same switch can be much more complicated than stupidly true false.
PS: these are language features, you do not need to use them, but I think it will not hurt anyone to know about it ..
Adding a handler is better using DOM2 , not DOM0 .
let tr = document.createElement('tr'); tr.addEventListener('click',function() { //Some code; }); DOM2 , but then I realized that I was putting you in a foolish position, with the general question “What is the difference?”, Since the question was changed. Decided that it is better to delete the answer completely and answer again. PS I hope you now ask a similar question. :-) - Ilya IndigoDOM2 is a more modern method, for me this alone is enough. 2 DOM0 makes sense to use only when we specify a handler through an HTML attribute, for example onclick 3 In the case of the declaration of a new handler DOM0, it will overwrite the old one, including the one that was defined through the HTML attribute. 4 It can not be clearly removed. - Ilya IndigoSource: https://ru.stackoverflow.com/questions/34477/
All Articles