如何复制 javascript 中变量的值
How to copy the value of variable in javascript
我正在尝试将字符串变量复制到剪贴板。
我可以找到很多从 或
标签复制值的示例,但我的问题是如果我对变量进行更改然后我想复制它,例如这个示例
var num1= getNum1();
var num2= getNum2();
var result = ((num1*num2)/3)-1
...//copy result value
alert("your results has been copied");
我得到了解决方案
var dummy = document.createElement("input");
//dummy.style.display = 'none'
document.body.appendChild(dummy);
//$(dummy).css('display','none');
dummy.setAttribute("id", "dummy_id");
//dummy.setAttribute('value', document.URL + '; ' + document.title)
dummy.setAttribute('value', textX) //TEXTX is the value of variable
//document.getElementById("dummy_id").value=val;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
var getNum1 = function() {
return 1;
};
var getNum2 = function() {
return 2;
};
var num1 = getNum1();
var num2 = getNum2();
var result = ((num1 * num2) / 3) - 1;
var executeCopy = function() {
var copyhelper = document.createElement("input");
copyhelper.className = 'copyhelper'
document.body.appendChild(copyhelper);
copyhelper.value = result;
copyhelper.select();
document.execCommand("copy");
document.body.removeChild(copyhelper);
};
document.getElementById('mybutton').addEventListener('click', function() {
executeCopy();
alert("your results has been copied");
});
.copyhelper {
position: absolute;
}
<button id='mybutton'>Copy to clipboard</button>
希望对您有所帮助!
我正在尝试将字符串变量复制到剪贴板。
我可以找到很多从 或
标签复制值的示例,但我的问题是如果我对变量进行更改然后我想复制它,例如这个示例
var num1= getNum1();
var num2= getNum2();
var result = ((num1*num2)/3)-1
...//copy result value
alert("your results has been copied");
我得到了解决方案
var dummy = document.createElement("input");
//dummy.style.display = 'none'
document.body.appendChild(dummy);
//$(dummy).css('display','none');
dummy.setAttribute("id", "dummy_id");
//dummy.setAttribute('value', document.URL + '; ' + document.title)
dummy.setAttribute('value', textX) //TEXTX is the value of variable
//document.getElementById("dummy_id").value=val;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
var getNum1 = function() {
return 1;
};
var getNum2 = function() {
return 2;
};
var num1 = getNum1();
var num2 = getNum2();
var result = ((num1 * num2) / 3) - 1;
var executeCopy = function() {
var copyhelper = document.createElement("input");
copyhelper.className = 'copyhelper'
document.body.appendChild(copyhelper);
copyhelper.value = result;
copyhelper.select();
document.execCommand("copy");
document.body.removeChild(copyhelper);
};
document.getElementById('mybutton').addEventListener('click', function() {
executeCopy();
alert("your results has been copied");
});
.copyhelper {
position: absolute;
}
<button id='mybutton'>Copy to clipboard</button>
希望对您有所帮助!