如何为 javascript 生成的文本框附加 OnClick 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2226953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to attach OnClick event for a javascript generated textbox?
提问by Asaph
I have a table row which contains a textbox and it has an onclick which displays a JavaScript calendar... I am adding rows to the table with textbox, but I don't know how to attach onclick event to the JavaScript generated textbox...
我有一个包含文本框的表格行,它有一个显示 JavaScript 日历的 onclick ......我正在用文本框向表格中添加行,但我不知道如何将 onclick 事件附加到 JavaScript 生成的文本框.. .
<input class="date_size_enquiry" type="text" autocomplete="off"
onclick="displayDatePicker('attendanceDateadd1');" size="21" readonly="readonly"
maxlength="11" size="11" name="attendanceDateadd1" id="attendanceDateadd1"
value="" onblur="per_date()" onchange="fnloadHoliday(this.value);">
And my JavaScript generates a textbox,
我的 JavaScript 生成了一个文本框,
var cell2 = row.insertCell(1);
cell2.setAttribute('align','center')
var el = document.createElement('input');
el.className = "date_size_enquiry";
el.type = 'text';
el.name = 'attendanceDateadd' + iteration;
el.id = 'attendanceDateadd' + iteration;
el.onClick = //How to call the function displayDatePicker('attendanceDateadd1');
e1.onblur=??
e1.onchange=??
cell2.appendChild(el);
回答by Asaph
Like this:
像这样:
var el = document.createElement('input');
...
el.onclick = function() {
displayDatePicker('attendanceDateadd1');
};
BTW: Be careful with case sensitivity in the DOM. It's "onclick", not "onClick".
顺便说一句:注意 DOM 中的区分大小写。是"onclick",不是"onClick"。
回答by Shawn Steward
el.onclick = function(){
displayDatePicker(this.id);
};
回答by Alconja
Taking your example, I think you want to do this:
以您为例,我认为您想这样做:
el.onclick = function() { displayDatePicker(el.id); };
The only trick is to realise why you need to wrap your displayDatePickercall in the function() { ... }code. Basically, you need to assign a function to the onclickproperty, however in order to do this you can't just do el.onclick = displayDatePicker(el.id)since this would tell javascript to execute the displayDatePickerfunction and assign the result to the onclickhandler rather than assigning the function call itself. So to get around this you create an anonymous function that in turn calls your displayDatePicker. Hope that helps.
唯一的技巧是了解为什么需要将displayDatePicker调用封装在function() { ... }代码中。基本上,您需要为该onclick属性分配一个函数,但是为了做到这一点,您不能这样做,el.onclick = displayDatePicker(el.id)因为这会告诉 javascript 执行该displayDatePicker函数并将结果分配给onclick处理程序,而不是分配函数调用本身。所以为了解决这个问题,你创建了一个匿名函数,反过来调用你的displayDatePicker. 希望有帮助。
回答by Arthur Araújo
HTML5/ES6 approach:
HTML5/ES6 方法:
var el = document.createElement('input')
[...]
el.addEventListener('click', function () {
displayDatePicker('attendanceDateadd1')
})

