Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In the interests of avoiding confusing myself with what function does what, I would always start with a closure, until I needed to reduce memory usage:</p> <pre><code>var dofocus = function(){element.focus()}; dofocus(); </code></pre> <p>If you're in a loop and <code>element</code> is changing, you can use a function that returns another function: <code>(function(e,m){return function(){e[m]()}})(element, method)</code></p> <p><strong>Edit</strong>: On a reread of the question, I'm thinking the reason your code doesn't work is because you're passing in the value of some variable named 'focus' and not the string method name 'focus', or rather the focus function (is it defined elsewhere?)</p> <p><strong>Edit</strong>: This works:</p> <pre><code>&lt;html&gt;&lt;title&gt;test&lt;/title&gt;&lt;script&gt; function foo (id, method, args) { var d = {"id": id, "method": method, "args": args}; // ... time passes var e = document.getElementById(d.id); // test exists var f = e[d.method]; // test exists var a = d.args; // test is an array f.apply(e, a); } &lt;/script&gt;&lt;body id="thebody"&gt; &lt;p&gt; &lt;button onclick="foo('bar', 'setSelectionRange', [4,6]);"&gt;select&lt;/button&gt; &lt;button onclick="foo('bar', 'focus', []);"&gt;focus&lt;/button&gt; &lt;input type="text" id="bar" value="foo bar baz"&gt; &lt;p&gt; &lt;button onclick="foo('thebody', 'appendChild', [document.createTextNode(new Date())]);"&gt;body&lt;/button&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p><strong>Edit</strong>: And if passing functions was the issue, you can always pass an optional method name and test whether the method is a string or a function, then be able to use 'focus' or a custom function without having to place it on the element.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload