It is not possible to include a Function
instance within a string.
If the buttons
variable is declared globally, it can be accessed by code within the onclick
event handler attribute:
var htmlButton = '<button type="button" onclick="buttons[\''+buttonName+'\']()">'+ buttonName + '</button>';
However, the above method does not handle escaping characters properly, which could lead to security vulnerabilities if buttonName
contains certain special characters like <
, &
, '
, or "
. To avoid this, these characters need to be escaped in both JavaScript and HTML where the strings are being embedded.
A more efficient approach is to refrain from creating HTML using concatenated strings. Instead, utilize DOM methods and native JavaScript objects to build your elements, thereby eliminating the complexities of dealing with nested strings.
var button = document.createElement('button');
button.type = 'button';
button.appendChild(document.createTextNode(buttonName));
button.onclick = buttons[buttonsName];