简体   繁体   中英

Jquery closest with ClipboardJS

I make a simple coupon clipper with ClipboardJS. My purpose is that when the user clicks on the Coupon button to clip it (copy). The Coupon will display the string Copied, then return to show the original Coupon after a moment.

Unfortunately, if there are two or more coupons on the same page, the returned value will always be the first Coupon. I tried to play around with jQuery closest, but I couldn't figure it out.

Here is my code:

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js"></script>
<p>
Clip Coupon <button class="coupon_clipper" data-clipboard-text="10PERCENT">10PERCENT</button> to receive 10% discount for order over 100$
</p>
<p>
Clip Coupon <button class="coupon_clipper" data-clipboard-text="1PERCENT">1PERCENT</button> to receive 1% discount for order over 100$
</p>

<style>
.coupon_clipper {
  border-style: dashed;
}
</style>

Javascript

<script>var cClip = new ClipboardJS('.coupon_clipper');

cClip.on('success', function(e) {
  $(e.trigger).text('Clipped');
  e.clearSelection();
  setTimeout(function() {
    $(e.trigger).text($('.coupon_clipper').closest('.coupon_clipper').attr('data-clipboard-text'));
  }, 250);
});
</script>

JSFiddle:

https://jsfiddle.net/whitecrown/tckd1820/3/

e.trigger return the element you clicked. So you can use that to get the attribute as well as to set text.

Notice

let button = e.trigger;
setTimeout(function() {
  $(button).text($(button).attr('data-clipboard-text'));
}, 250);

 var cClip = new ClipboardJS('.coupon_clipper'); cClip.on('success', function(e) { let button = e.trigger; e.clearSelection(); $(button).text('Clipped'); setTimeout(function() { $(button).text($(button).attr('data-clipboard-text')); }, 250); });
 .coupon_clipper { border-style: dashed; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.4/clipboard.min.js"></script> <p> Clip Coupon <button class="coupon_clipper" data-clipboard-text="10PERCENT">10PERCENT</button> to receive 10% discount for order over 100$ </p> <p> Clip Coupon <button class="coupon_clipper" data-clipboard-text="1PERCENT">1PERCENT</button> to receive 1% discount for order over 100$ </p>

$('.coupon_clipper').closest('.coupon_clipper') this will return always first, you have to think with respective to action you performed on which element. and in your case it will be the same so you can you directly e.trigger which returns the button you clicked.

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