【发布时间】: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');
});
我可能需要each 和closest 之类的东西,但我不知道如何应用它(
$('.field').each(function () {
var copyText = $('.field input');
$(this).on('click', '.copy', function () {
copyText.select();
document.execCommand('copy');
});
});
【问题讨论】:
-
您好,只需将
$('.field input')更改为$(this).prev()即可进行第一次尝试。 Working fiddle -
你为什么不把这个作为答案,我会感谢你的评估)