【问题标题】:how do i copy to clipboard with the input or placeholder name?如何使用输入或占位符名称复制到剪贴板?
【发布时间】:2017-11-18 00:01:08
【问题描述】:

我有一个简单的表格:https://jsfiddle.net/skootsa/8j0ycvsp/6/

<div class='field'>
<input placeholder='Nickname' type='text'>
</div>
<div class='field'>
<input placeholder='Age' type='text'>
</div>

如何获得一个复制每个输入框内容的按钮+“占位符”属性(或类名)?所以剪贴板结果看起来像这样:

昵称:Johnnyboy

年龄:22

【问题讨论】:

  • 可能与this重复

标签: javascript forms button onclick clipboard


【解决方案1】:

你需要:

  1. 创建一个不可见的元素来复制数据
  2. 从表单中获取数据并将其设置为上一个元素
  3. 选择它
  4. 调用document.execCommand('copy')将选中的文本复制到 剪贴板

我已经更新了你的小提琴,看看https://jsfiddle.net/8j0ycvsp/9/

如果你想要代码

function copyToClipboard() {

    /*get inputs from form */
    var inputs = document.querySelectorAll("#the-form input[type=text]");

    /*do a copy of placeholder and contents*/
    var clipboardText = ''
    for (var i = 0, input; input = inputs[i++];) {
        clipboardText += input.placeholder+': '+(input.value ? input.value : '' )+'\n';     
    }

    /*create hidden textarea with the content and select it*/
    var clipboard = document.createElement("textarea");
    clipboard.style.height = 0;
    clipboard.style.width  = 0;
    clipboard.value = clipboardText;
    document.body.appendChild(clipboard);
    clipboard.select();

    console.log(clipboard.value);

    /*do a copy fren*/
    try {
        if(document.execCommand('copy'))
            console.log('Much succes, wow!');
        else 
            console.log('Very fail, wow!');

    } catch (err) {        
        console.log('Heckin concern, unable to copy');
    }
}

【讨论】:

  • 由于某种原因它没有更新我的剪贴板
  • @amy-gr8njr 我已经添加了代码并更新了小提琴。在小提琴示例中,Javascript 加载类型需要是“No wrap - in ”。现在应该可以工作了!
【解决方案2】:

那就试试吧

var input = document.querySelectorAll('.field input');

document.getElementById('submit').addEventListener('click', function () {
	var innerHTMLText = "";
	for (var i = 0; i < input.length; i++) {
		innerHTMLText += input[i].placeholder + ':' + input[i].value + '      ';
	}
	console.log(innerHTMLText);
	document.getElementsByClassName('bix')[0].innerHTML = innerHTMLText;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多