0

i am trying to add event to element through an function like as follow

function addevent(elements,event_n,function_n,param_trs)
    {
          var i = elements.length; 
       while (i--){ 
           function_name=function_n+"(this.getAttribute('"+param_trs+"'))";
           //function_name=function_n ;
           elements[i].addEventListener(event_n,function_name);
          // console.log(function_name);
       }
    }

this is giving error :

TypeError: Value not an object.

at elements[i].addEventListener(event_n,function_name);

so i can coll them as follow

addevent(document.querySelectorAll('tr'),'click','view_details','request_id');

to add click event to all tr example :

<tr request_id="5" onclick="view_details(this.getAttribute('request_id'))" >

or

<tr request_id="5" onclick="view_details(this)" >

how can i do it through function like above

Swarna Sekhar Dhar
  • 550
  • 1
  • 8
  • 25

1 Answers1

1

It really is a bad idea to pass function names as string. The same goes for appending code in string format, like "(this.getAttribute('"+param_trs+"'))". This will need to be parsed, much like eval does. It is inefficient, and may lead to the problems related to eval.

Functions can be passed as arguments, not as strings, but as real function references. Secondly, it would be more appropriate that the event handler function retrieves the attribute value at the moment it executes, not before.

So here is a snippet that presents the idea. The demo will take the attribute data-inc to determine with how much a number should be incremented.

function addEventListeners(elements, event_n, attrib_n, func) {
    var i = elements.length; 
    while (i--) { 
        // bind the attribute name as argument to the function.
        elements[i].addEventListener(event_n, func.bind(elements[i], attrib_n));
    }
}

// Demo:
addEventListeners(document.querySelectorAll('span'), 'click', 'data-inc',
    function(attrib_n) { 
        this.textContent = +this.textContent + +this.getAttribute(attrib_n);
    }
);
span { border: 1px solid; padding: 2px; background: #C0FFC0 }
Click on numbers to change them:<br>
Per 5: <span data-inc="5">0</span> Per 7: <span data-inc="7">0</span>
Per 1: <span data-inc="1">0</span>
Per -1: <span data-inc="-1">0</span>
Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286