How to copy the value of variable in javascript [duplicate]

你说的曾经没有我的故事 提交于 2019-12-11 17:33:36

问题


I'm trying to copy string variable to clipboard.

I could find a lot of examples that copy the values from < input > or < p > tags, But my problem in case I make a changes on variable then I want to copy it such as this example

var num1= getNum1();
var num2= getNum2();
var result = ((num1*num2)/3)-1
...//copy result value
alert("your results has been copied");

回答1:


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>

Hope it helps!




回答2:


I got the solution

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);


来源:https://stackoverflow.com/questions/48370896/how-to-copy-the-value-of-variable-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!