简体   繁体   中英

Dynamically Create OnClick Event Javascript

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?

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']);
});

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

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>";

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM