【问题标题】:Copying the contents of multiple inputs to the clipboard将多个输入的内容复制到剪贴板
【发布时间】:2021-11-13 14:49:16
【问题描述】:

我有一些带有一些文本的字段。每个字段都有自己的用于复制到剪贴板的按钮。但我无法让它以任何方式正常工作。

结构如下

<div class="field">
    <input type="text" value="some text" />
    <span class="copy">Copy!</span>
</div>
<div class="field">
    <input type="text" value="some text2" />
    <span class="copy">Copy!</span>
</div>
<div class="field">
    <input type="text" value="some text3" />
    <span class="copy">Copy!</span>
</div>

如果有一个字段,下面的代码可以工作,但是如果有多个呢?

$('.field').on('click', '.copy', function () {
    var copyText = $('.field input');
    copyText.select();
    document.execCommand('copy');
});

我可能需要eachclosest 之类的东西,但我不知道如何应用它(

$('.field').each(function () {
    var copyText = $('.field input');
    $(this).on('click', '.copy', function () {
        copyText.select();
        document.execCommand('copy');
    });
});

【问题讨论】:

  • 您好,只需将 $('.field input') 更改为 $(this).prev() 即可进行第一次尝试。 Working fiddle
  • 你为什么不把这个作为答案,我会感谢你的评估)

标签: jquery copy


【解决方案1】:

你需要使用 $(this) 和 prevAll()

https://api.jquery.com/prevall/

$('.field').on('click', '.copy', function () {
    var copyText = $(this).prevAll("input"); 
    var copyTextVal = $(copyText).val();
    $(copyText).select();
    document.execCommand('copy');
    
    // debug infos 
    console.clear();
    console.log(copyTextVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field">
    <input type="text" value="some text" />
    <span class="copy">Copy!</span>
</div>
<div class="field">
    <input type="text" value="some text2" />
    <span class="copy">Copy!</span>
</div>
<div class="field">
    <input type="text" value="some text3" />
    <span class="copy">Copy!</span>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2011-04-26
    • 2014-07-19
    相关资源
    最近更新 更多