Skip to main content
 首页 » 编程设计

jquery之如何将 ZeroClipboard 剪辑粘到新插入的元素上

2026年07月24日8jpfss

我正在尝试编写一个基本的博客平台,并且我希望为用户提供将预 block 中的代码复制到剪贴板的功能。

我正在使用ZeroClipboard为了达成这个。文档准备就绪后,我会循环访问页面上的每个 pre,并向其中添加一个剪贴板项目,如下所示:

    $(document).ready(function() { 
 
        ZeroClipboard.setMoviePath( 'ZeroClipboard/ZeroClipboard.swf' ); 
        var preNum = 1 
 
        $('pre').each(function() { 
            // Get a unique id for the element I will be inserting 
            var id = 'copy-btn-' + preNum++ 
            // Capture the text to be copied to the clipboard 
            var text = $(this).text() 
            // Insert the element, just before this 
            $('<div class="copy-btn" id="' + id + '-cont"><i class="icon-file icon-white" id="' + id + '"></i></div>').insertBefore(this) 
            // Capture the newly inserted element 
            var elem = $(this).prev() 
 
            // Create the clip, and glue it to the element 
            var clip = new ZeroClipboard.Client(); 
            clip.setText(text) 
            clip.glue(elem) 
       }) 
   }); 

当我尝试执行此操作时,JavaScript 控制台报告:Uncaught TypeError: Cannot read property 'zIndex' of undefined

我目前对问题的理解是,当我尝试将剪辑粘合到插入的元素时,插入的元素在 dom 中尚不可用,这就是没有发生粘合的原因。

有人知道我怎样才能做到这一点吗?

请您参考如下方法:

来自Gluing instructions :

You can pass in a DOM element ID (as shown above), or a reference to the actual DOM element object itself.

您的代码不起作用,因为您向其传递了 jQuery 对象。

您可以传递 ID:

clip.glue(id + '-cont') 

或者实际的 DOM 元素引用:

clip.glue(elem[0]) 

上面的示例使用 .get() 的简写形式jQuery 对象方法。