2012-10-26 62 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

相關問題