[英]Dynamically Create OnClick Event Javascript
我试图以编程方式创建一个具有onclick事件的按钮。
var removeFunction = "removeEmployee(" + "'" + phone + "'" + "," + "'" + pin + "'" + "," + "'" + employees[i].ID + "'" + ")";
var removeButton = "<a onclick='" + removeFunction + "' " + "data-role='button' data-icon='delete' data-iconpos='notext'></a>";
我在与上面动态创建的代码相同的javascript文件中具有此功能。 我认为这很麻烦,因为我需要在字符串参数周围添加引号。 上面的代码是一种尝试,但是如果我查看创建的标记,它将读取..
onclick="removeEmployee("
是什么让其余的即时通讯无法确定是什么? 只要我在javascript文件中有一个名为“ removeEmployee”的函数,此命令也可以运行吗?
不是避免这个问题,而是为什么您不这样做:
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']);
});
在XML代码中,可以使用双引号或单引号设置字符串。 在这种情况下,应该使用单引号,然后可以在字符串内使用双引号。
像这样:
onclick='removeEmployee("45681", 1, "test")'
或反之亦然:
onclick="removeEmployee('45681', 1, 'test')"
当您编写提到的代码时,HTML解析器看起来像这样:
<element onclick='removeEmployee(' 45681=', 1, ' test=')' />
在这种情况下,您的元素具有3个具有三个不同名称的属性,而不仅仅是“ onclick”属性和IT IS WRONG 。
干杯
尝试:
var removeFunction = "removeEmployee('" + phone + "','" + pin + "','" + employees[i].ID + "')";
也:
var removeButton = "<a onclick='" + removeFunction + "' data-role='button' data-icon='delete' data-iconpos='notext'></a>";
你可以用
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.