2012-10-26 58 views
5

我正在尝试写一个基本的博客平台,并且我想让用户能够将代码块中的代码复制到他们的剪贴板。如何将()ZeroClipboard剪辑粘贴到新插入的元素上?

我正在使用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中尚不可用,这就是为什么不发生粘合的原因。

有人知道我怎么能做到这一点?

回答

2

Gluing instructions

可以在DOM元素ID传递(如上所示),或以 实际DOM元素对象本身的引用。

你的代码不起作用,因为你传递了一个jQuery对象。

可以传递的ID:

clip.glue(id + '-cont') 

或实际的DOM元素参考:

clip.glue(elem[0]) 

以上的例子使用针对.get() jQuery对象方法的简写。

+1

伟大的呼唤。谢谢您的帮助。 – finiteloop

相关问题