微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jquery – 如何将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:无法读取未定义的属性’zIndex’

我目前对这个问题的理解是,当我试图将夹子粘到它上面时,插入的元件还没有在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对象方法的简写.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐