Reputation: 8188
I am attempting to create a button that has an onclick event programmically..
var removeFunction = "removeEmployee(" + "'" + phone + "'" + "," + "'" + pin + "'" + "," + "'" + employees[i].ID + "'" + ")";
var removeButton = "<a onclick='" + removeFunction + "' " + "data-role='button' data-icon='delete' data-iconpos='notext'></a>";
I have this function in the same javascript file as the the dynamically created code above. I think it is breaking because I need to add quotes around the string parameters. The above code is an attempt to that but if I look at the created markup it reads..
onclick="removeEmployee("
Something is making the rest cut off im not sure what? Also will this run as long as I have a funcition named "removeEmployee" located in my javascript file?
Upvotes: 0
Views: 2508
Reputation: 10057
Not to avoid the question, but why wouldn't you do something like this instead:
var bindEvent = function(el, event, handler) {
if (el.addEventListener){
el.addEventListener(event, handler, false);
} else if (el.attachEvent){
el.attachEvent('on'+event, handler);
}
}
var removeButton = document.createElement("a");
removeButton.setAttribute("data-role", "button");
removeButton.setAttribute("data-icon", "delete");
removeButton.setAttribute("data-iconpos", "notext");
bindEvent(removeButton, "click", function(){
removeEmployee(phone, pin, employees[i]['id']);
});
Upvotes: 1
Reputation: 5199
Try:
var removeFunction = "removeEmployee('" + phone + "','" + pin + "','" + employees[i].ID + "')";
Also:
var removeButton = "<a onclick='" + removeFunction + "' data-role='button' data-icon='delete' data-iconpos='notext'></a>";
Upvotes: 0
Reputation: 3518
In XML codes, you can use either double-quotes or single-quotes for setting strings. In this matter, you should use single-quote, then you can use double-quotes inside your string.
Like this:
onclick='removeEmployee("45681", 1, "test")'
Or visa versa:
onclick="removeEmployee('45681', 1, 'test')"
When you write the code you mentioned, it seems like this to the HTML parser:
<element onclick='removeEmployee(' 45681=', 1, ' test=')' />
In this situation, your element has 3 attributes with three different names, not just "onclick" attribute and IT IS WRONG.
Cheers
Upvotes: 0
Reputation: 288010
You could use
var a=document.createElement('a'),
attrs={data-role:'button',data-icon:'delete',data-iconpos:'notext'};
for(var i in attrs){a.setAttribute(i,attrs[i]}
a.onclick=function(){
removeEmployee(phone,pin,employees[i].ID);
}
Upvotes: 0