动态创建OnClick事件Javascript

时间:2012-09-10 21:16:21

标签: 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”的函数,它也会运行吗?

4 个答案:

答案 0 :(得分:1)

不要回避这个问题,但为什么你不会这样做呢:

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

答案 1 :(得分:0)

在XML代码中,您可以使用双引号或单引号来设置字符串。在这个问题上,你应该使用单引号,然后你可以在你的字符串中使用双引号。

像这样:

onclick='removeEmployee("45681", 1, "test")'

反之亦然:

onclick="removeEmployee('45681', 1, 'test')"

当你编写你提到的代码时,对HTML解析器来说似乎是这样:

<element onclick='removeEmployee(' 45681=', 1, ' test=')' />

在这种情况下,您的元素有3个属性,有三个不同的名称,而不仅仅是“onclick”属性和错误

干杯

答案 2 :(得分:0)

尝试:

var removeFunction = "removeEmployee('" + phone + "','" + pin + "','" + employees[i].ID + "')"; 

此外:

var removeButton = "<a onclick='" + removeFunction + "' data-role='button' data-icon='delete' data-iconpos='notext'></a>";

答案 3 :(得分:0)

您可以使用

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);
}
相关问题