如何为 JavaScript 生成的文本框附加 onclick 事件?
我有一个表行,其中包含一个文本框,它有一个显示 JavaScript 日历的 onclick...我正在使用文本框向表中添加行,但我不知道如何将 onclick 事件附加到 JavaScript 生成的文本框。 我的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);">
生成一个文本框,
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);
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...
<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,
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
HTML5/ES6 方法:
HTML5/ES6 approach:
像这样:
顺便说一句:请注意 DOM 中的大小写敏感性。它是
“onclick”
,而不是“onClick”
。Like this:
BTW: Be careful with case sensitivity in the DOM. It's
"onclick"
, not"onClick"
.以您的示例为例,我认为您想要这样做:
唯一的技巧是意识到为什么需要将
displayDatePicker
调用包装在function() { ... }
中代码。基本上,您需要为onclick
属性分配一个函数,但是为了做到这一点,您不能只执行el.onclick = displayDatePicker(el.id)
因为这将告诉 javascript 执行displayDatePicker
函数并将结果分配给onclick
处理程序,而不是分配函数调用本身。因此,为了解决这个问题,您创建了一个匿名函数,该函数依次调用您的displayDatePicker
。希望有帮助。Taking your example, I think you want to do this:
The only trick is to realise why you need to wrap your
displayDatePicker
call in thefunction() { ... }
code. Basically, you need to assign a function to theonclick
property, however in order to do this you can't just doel.onclick = displayDatePicker(el.id)
since this would tell javascript to execute thedisplayDatePicker
function and assign the result to theonclick
handler rather than assigning the function call itself. So to get around this you create an anonymous function that in turn calls yourdisplayDatePicker
. Hope that helps.