RawClicked I have old assign method of tr for event like this:
<tr ondblclick="RawClicked(this) .......
and I want to attach the event in JavaScript code like this, and delete assigning the event handler in HTML tag <tr .... > :
var element = document.getElementById("CustomersTable").getElementsByTagName("tr");
AssigningEventHandles(element, "dblclick", RawClicked(this));
function AssigningEventHandles(element, event, handler) {
if (element.addEventListener) {
element.addEventListener(event, handler, false);
}
else if (element.attachEvent) {
element.attachEvent("on"+ event, handler);
}
}
function RawClicked(raw) {
var rawDoubleClicked = raw.id;
alert(rawDoubleClicked);
}
So how can I pass the parameter this to the function in this case?
In your example
elementis a collection of nodes, not a single element, so you can’t add event listeners this way. You may iterate over this collection of nodes or use event delegation and attach event listener to the<table>.In this line
AssigningEventHandles(element, "dblclick", RawClicked(this));RawClicked is executed withthisbound to the global object. So the argument passed ashandlertoAssigningEventHandlesis the result of this function, which is void. You should pass the function like this:AssigningEventHandles(element, "dblclick", RawClicked);and then usethis.idinstead ofraw.idinRawClicked.Fixed code:
http://jsfiddle.net/WU76d/