event.clipboardData是未定义的。

9

我正在尝试访问浏览器中的“粘贴”事件并重写它。但是,event.clipboardData未定义。目前我只有这个:

function handlePaste (event) {

    event.preventDefault();

    console.log("Handling paste");
    console.log(event.clipboardData);
}

编辑:

这是 Angular 指令的一部分,我在 Chrome 中运行它:

app.directive('safePaste', [function() {

function handlePaste (event) {

    event.preventDefault();

    console.log("Handling paste");
    console.log(event.clipboardData);
}

/*
 * Declaration
 */
var declaration = {};

declaration.restrict = 'A';

declaration.link = function(scope, element, attr) {
    // Attach the paste handler
    element.on('paste', handlePaste);

    // Register to remove the paste handler
    scope.$on('$destroy', function() {
        element.off('paste', handlePaste);
    });
};

return declaration;
} 
]);

HTML:

<li ng-repeat="note in notes | reverse">
     <a id="note" href="#">
        <h2 id="note-title" data-note-id="{{ note.id }}" safe-paste> {{ note.title | limitTo : 16 }}</h2>
            <p id="note-content" data-note-id="{{ note.id }}" safe-paste> {{ note.text | limitTo : 200 }} </p>
            <p id="info-note-save" hidden="true" class="text-center">Press enter to save</p>
     </a>
</li>

你是如何调用这个函数的? - dsharew
event 变量是什么类型?你认为它为什么有 clipboardData 属性? - Regent
请指明您正在测试代码的浏览器。 - dsharew
兄弟,我从没用过Angular。你能把你的代码放到jsfiddle上,这样就可以帮我设置环境了。我的意思是包括Angular库、jQuery库等。 - dsharew
1个回答

19

最近我遇到了类似的问题,我试图拦截粘贴事件。我使用了这里的代码:

function handlePaste (e) {
    var clipboardData, pastedData;

    // Get pasted data via clipboard API
    clipboardData = e.clipboardData || window.clipboardData;
    pastedData = clipboardData.getData('Text').toUpperCase();

    if(pastedData.indexOf('E')>-1) {
        //alert('found an E');
        e.stopPropagation();
        e.preventDefault();
    }
};
我改变了clipboardData这一行,改为:
clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;

现在它正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接