簡體   English   中英

動態創建OnClick事件Javascript

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM