我的网站在 DOM 上有很多动态内容。如何委托(delegate) numeric() 函数?
我知道我必须做这样的事情:
$(document.body).on('.js-numeric', 'keydown' (change etc.) function() {});
但我不确定如何插入 numeric()
函数。如果我想对静态内容使用数字函数,它可以正常工作,如下所示:
$(".js-numeric").numeric();
最佳答案
如果您的元素位于 body
标记中,您可以执行以下操作:
$(document.body).on('keydown', '.js-numeric', function() {})
你交换了参数,如果你 read the docs你可以看到:
.on( events [, selector ] [, data ], handler )
在选择器
之前获取事件
,而不是像您现在那样采取相反的方式。
如果您阅读我上面的代码片段读比您编写的代码更符合逻辑(不是我编写了更清晰的代码,而是 jQuery 开发人员考虑了这些事情:))
这会将 keydown
事件从 document.body
委托(delegate)给任何动态添加的 .js-numeric
元素。
如果你想在已经被 keydown
ed 的元素上调用 .numeric()
,那么你可以这样写:
$(document.body).on('keydown', '.js-numeric', function() {
// $(this) is the element that triggered the event
$(this).numeric();
})
关于Javascript 委托(delegate)和 numeric() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34155126/