in creating a button from an javascript object i am doing the following :
for (buttonName in buttons){
开发者_开发百科 var htmlbutton = '<button type="button" onclick="'+buttons[buttonName]()+'">'+buttonName+'</button>'
}
I am trying to attach the function to an onclick event but i cant figure out the right sythanx
thanks in advance
You can't embed a Function
instance inside a string.
If the buttons
variable is global, it will be accessible to code inside the onclick
event handler attribute:
var htmlbutton= '<button type="button" onclick="buttons[\''+buttonName+'\']()">'+buttonName+'</button>'
However, there is no escaping in the above, so you will have problems (potentially security problems) if buttonName
can ever contain a <
, &
, '
or "
character. You would have to escape these in various ways for the JavaScript and HTML you're embedding the strings in.
Much better is to avoid slinging strings to make HTML at all. Then you can use DOM methods and native JavaScript objects and avoid all the confusing nastiness of strings-inside-strings.
var button= document.createElement('button');
button.type= 'button';
button.appendChild(document.createTextNode(buttonName));
button.onclick= buttons[buttonsName];
Try to replace your code with:
for (buttonName in buttons)
{
var htmlbutton =
'<input' +
' type="button"' +
' value="' + (buttons[buttonName]).replace(/"/gi, """) + '"' +
' onclick="' + (buttons[buttonName]).replace(/"/gi, """) + '()"/>';
}
Edited to clarify:
As there's no reliable <button>
tag in HTML.
From W3School website:
Important: If you use the button element in an HTML form, different browsers will submit different values. Internet Explorer will submit the text between the
<button>
and</button>
tags, while other browsers will submit the content of the value attribute. Use the<input>
element to create buttons in an HTML form.
I guess you're looking for something like this:
for(buttonName in buttons) {
var htmlbutton = '<button type="button" onclick="window.buttons[\''+buttonName+'\']()">'+buttonName+'</button>';
Instead of printing the whole function in the onclick attribute, this just prints out the callable function name. Just make sure that buttons
is in the correct scope.
Though using jquery isnt required in this case, the code i am writing is for a jquery plugin. So far this is the best solution i could come up with :
$.each(buttons, function(name, fn) {
$('<input type="button" value="'+name+'" />').click(function() { fn.apply() });
});
I have yet to find out whether there are any pitfalls in using the call or apply property but so far this works like charm.
your thoughts and comments are very well appreciated
精彩评论