简体   繁体   English

如何为 JavaScript 生成的文本框附加 onclick 事件?

[英]How to attach onclick event for a JavaScript generated textbox?

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

Like this:像这样:

var el = document.createElement('input');
...
el.onclick = function() {
    displayDatePicker('attendanceDateadd1');
};

BTW: Be careful with case sensitivity in the DOM.顺便说一句:注意 DOM 中的区分大小写。 It's "onclick" , not "onClick" .它是"onclick" ,而不是"onClick"

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 displayDatePicker call in the function() { ... } code.唯一的技巧是意识到为什么需要在function() { ... }代码中包装displayDatePicker调用。 Basically, you need to assign a function to the onclick property, however in order to do this you can't just do el.onclick = displayDatePicker(el.id) since this would tell javascript to execute the displayDatePicker function and assign the result to the onclick handler rather than assigning the function call itself.基本上,您需要为onclick属性分配一个函数,但是为了做到这一点,您不能只执行el.onclick = displayDatePicker(el.id)因为这会告诉 javascript 执行displayDatePicker函数并将结果分配给onclick处理程序,而不是分配函数调用本身。 So to get around this you create an anonymous function that in turn calls your displayDatePicker .因此,为了解决这个问题,您创建了一个匿名函数,该函数反过来调用您的displayDatePicker Hope that helps.希望有帮助。

el.onclick = function(){
  displayDatePicker(this.id);
};

HTML5/ES6 approach: HTML5/ES6 方法:

var el = document.createElement('input')

[...]

el.addEventListener('click', function () {
  displayDatePicker('attendanceDateadd1')
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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