我目前正在尝试将输入的所有功能绑定(bind)到文档,因为我正在使用 AJAX 重新加载输入。我已经试过了,但这很奇怪,因为它不再起作用了:
let val = jQuery("input#val");
jQuery(document).on('keypress', val, function (e) {
if (8 !== e.which && 0 !== e.which && (e.which < 48 || e.which > 57)) return !1
});
jQuery(document).on('keyup', val, function () {
jQuery(this).val(function (e, t) {
return t.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ".")
})
});
jQuery(document).on('bind', val, function (e) {
e.preventDefault()
});
jQuery(document).on('focus', val, function () {
jQuery(this).parent().addClass("has-focus");
}).blur(function () {
jQuery(this).parent().removeClass("has-focus");
});
我做错了什么?
最佳答案
当使用委托(delegate)事件处理程序时,选择器参数需要是一个字符串,而不是您当前使用的 jQuery 对象。
请注意在下面的示例中,在 document.ready 事件处理程序中使用了 $
别名,它允许您通过更简洁的 保留对
变量。 jQuery
的引用>$
最后,检查 blur
事件是否按预期工作,因为您将其附加到 document
,而不是 input
。我也更新了委托(delegate)事件的答案。试试这个:
jQuery(function($) {
let val = 'input#val'; // this needs to be a string
$(document).on('keypress', val, function(e) {
if (8 !== e.which && 0 !== e.which && (e.which < 48 || e.which > 57)) return !1
});
$(document).on('keyup', val, function() {
$(this).val(function(e, t) {
return t.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ".")
})
});
$(document).on('bind', val, function(e) {
e.preventDefault()
});
$(document).on('focus', val, function() {
$(this).parent().addClass("has-focus");
});
$(document).on('blur', val, function() {
$(this).parent().removeClass("has-focus");
});
});
关于javascript - 输入 JS 绑定(bind)函数在重写后不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57303950/