简体   繁体   中英

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.

<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. 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. 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. so, in case the data is fetched from ajax, clipboard, won't binds them as u wish to. 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 .

<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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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