$.fn.pasteEvents = function( delay ) {
if (delay == undefined) delay = 20;
return $(this).each(function() {
var $el = $(this);
$el.on("paste", function() {
$el.trigger("prepaste");
setTimeout(function() { $el.trigger("postpaste"); }, delay);
});
});
};
在元素上调用此插件,然后您将获得粘贴之前和之后的回调事件
$("#some-element").on("postpaste", function() {
// do something
}).pasteEvents();
$( .. )调用在这里是多余的。由于此函数将成为 jQuery 对象的方法,因此上下文显然已经是 jQuery 对象,否则它将没有此方法,返回它将不会启用链式操作。创建 jQuery 对象仅在处理原始元素时才需要,例如在
$.each的回调中$("#some-element") .on("postpaste", function() { /* snip */ }).pasteEvents();由于它是在另一个调用之后立即调用的,因此顺序并不重要,但作为最佳实践,最好在绑定它们之前启用事件,而不是先绑定它们,然后再启用它们。因此,类似这样的
$("#some-element") .watchPasteEvents() .on("postpaste", function() { /* snip */ });$el.on("paste", function() { $el.trigger("prepaste"); setTimeout(function() { $el.trigger("postpaste"); }, delay); });这可能会导致在同一个元素上多次触发事件。如果用户有多个重叠的 jQuery 集合(例如
$('.foo')和$('.bar'),并且某些项目具有class="foo bar",就会发生这种情况。可以通过在数据对象中维护一个布尔值来修复这个问题,例如$.fn.watchpasteEvents = function (delay) { delay = delay || 20; return this.each(function () { var $el = $(this); if ($el.data('pasteEventsBound')) { return true; } $el .data('pasteEventsBound', true) .on('paste', function () { $el.trigger('prepaste'); setTimeout(function () { $el.trigger('postpaste'); }, delay); }); }); };谢谢 TeMc,这对我的代码来说是一个很好的改进!
粘贴事件的应用是什么?
那代码真棒!
@TC,
不错,但是 ‘pasteEventsBound’ 被添加(并设置为 ‘true’),而它从未被移除。所以这只能工作一次,直到页面刷新。