简体   繁体   English

如何在Ajax中使用剪贴板.js? (数据剪贴板)

[英]How to use clipboard.js with Ajax? (data-clipboard)

I have Clipboard.js working fine on my test site, I can copy using data-clipboard as such. 我在测试站点上的Clipboard.js运行良好,可以使用data-clipboard进行复制。

<a href="#">
<i class="icon-link icon-1x fa-fw" id="d_clip_button_x" data-clipboard-text="copythistext" title="Copy direct link"></i></a>
<script  type="text/javascript" src="copy/clipboard.min.js"></script>
<script  type="text/javascript"> var client = new Clipboard(  document.getElementById('d_clip_button_x') );</script>

But when I have content from an Ajax call the same code no longer functions. 但是当我收到来自Ajax调用的内容时,相同的代码将不再起作用。 I have read some ways and tutorials on how to get Ajax to work well with Clipboard.js but I can't seem to wrap my head around it. 我已经阅读了一些有关如何使Ajax与Clipboard.js一起良好工作的方法和教程,但是我似乎无法全神贯注于此。 As I understand it I need to retrigger the function, but how can I achieve that? 据我了解,我需要重新触发该功能,但是如何实现呢?

Thanks. 谢谢。

i tried on my end. 我尽力了。 clipboard.js uses extensive triggers to get the data attribute and binds when the page finishes loading. 剪贴板.js使用大量的触发器来获取data属性,并在页面加载完成时进行绑定。 so, in case the data is fetched from ajax, clipboard, won't binds them as u wish to. 因此,如果数据是从ajax,剪贴板中获取的,则不会按您希望的那样绑定它们。 for the solution, here is the trick. 对于解决方案,这是窍门。 first of all, make one generic copy button which works, give it a ID, suppose we give is d_clip_button_villa_XXX . 首先,使一个通用的复制按钮起作用,给它一个ID,假设我们给的是d_clip_button_villa_XXX

<a style="display:none" href="javascript:void(0);"> <i class="icon-link icon-1x fa-fw" id="d_clip_button_villa_XXX" data-clipboard-text="" title="Copy direct link"> </i> </a> <script type="text/javascript"> var client = new Clipboard( document.getElementById('d_clip_button_villa_XXX') ); </script>

now, instead of making same buttons, use any element like <a> tag and mention 2 events-> 现在,不要使用相同的按钮,而是使用<a>标记之类的任何元素并提及2个events->

<a href="#" onmouseover="copytxt('here is the text')" onclick="clkd(); return false;">copy</a>

now make two functions-> 现在做两个功能->

function copytxt(txt){ 
jQuery('#d_clip_button_villa_XXX').attr('data-clipboard-text', txt); 
} 

function clkd(){ 
jQuery('#d_clip_button_villa_XXX').click(); 
}

this will work with ajax also 这也可以与ajax一起使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM