我希望在 class="date"的输入元素上触发 focusout 事件,并驻留在 class='datatable' 的表中,无论是对于 DOM 中的元素还是动态添加的元素。对于动态添加的元素(使用createElement和appendChild),以下代码可以成功运行:
$('.datatable').on('focusout','tr td input', function(){
if (this.class == 'date') {
this.value = dateValid(this.value);
}
});
但是,对于加载到 DOM 中的元素,上面的代码不起作用。我也尝试了下面的代码,但它也不起作用:
$('.date').focusout(dateValid(this.value));
未触发 focusout 事件的输入元素的 HTML:
<table class="datatable">
<tr>
<td>Prospective Effective Date</td>
<td><input class="date" type="text" name="effectivedate"></td>
</tr>
<tr>
<td>Prospective Expiration Date</td>
<td><input class="date" type="text" name="expirationdate"></td>
</tr>
</table>
我对 JavaScript 非常陌生,非常感谢您的帮助!
最佳答案
我认为问题出在保留关键字“class”上:
if (this.class == 'date') {
//...
}
使用类名
if (this.className === 'date') {
//...
}
如果这不能解决问题。您可能会在现有表中附加额外的 table.datatable
元素,而不是 tr
元素。您可以通过将 focusout
绑定(bind)到 document
$(document).on('focusout','input.date', function(){
//...
});
关于javascript - 部分代码未触发 focusout 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741515/