简体   繁体   中英

Using javascript to copy text to clipboard

I know there are a couple of answers to this question but I am cross-eyed from looking at the multiplicity of choices. Here's the problem I'm trying to solve.

In a jQueryMobile program the user performs a search. A listview of the results is presented. (There could be a lot). It turns out the names of the results in the listview could be used in another input field in the application. So my thought is to let them click an icon which would put the results displayed in the listview on the the clipboard so that when they go to the other page in the application they can just press ^C (or CMD-c on the Mac) and the data will be loaded into the field.

I'm basically looking for the simplest solution if anyone has any insight.

You can try Clipboard.js .

It's a dependency free Javascript clipboard library, so no Flash/Java fallback. It has a declarative attribute API and a more configurable imperative API, that you can use to fine tune your specific use case.

To solve your problem, you would create the "copy" button as a HTML element.

<!-- Target -->
<input id="foo" value="DEFAULT_VALUE">

<!-- Trigger -->
<button class="btn" data-clipboard-target="#foo">
  <img src="assets/clippy.svg" alt="Copy to clipboard">
</button>

Then when a user copies text, you can display feedback based on the event you caught with the following handlers.

var clipboard = new Clipboard('.btn');

clipboard.on('success', function(e) {
  console.info('Action:', e.action);
  console.info('Text:', e.text);
  console.info('Trigger:', e.trigger);

  e.clearSelection();
});

clipboard.on('error', function(e) {
  console.error('Action:', e.action);
  console.error('Trigger:', e.trigger);
});

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