2016-03-26 18 views
6
<html> 
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" /> 
<p id="message" ></p> 

<script> 
function GetValue() 
{ 
    var myarray= new Array("item1","item2","item3"); 
    var random = myarray[Math.floor(Math.random() * myarray.length)]; 
    //alert(random); 
    document.getElementById("message").innerHTML=random; 
} 
</script> 

</html> 

to jest kod, a kiedy generuję losowe słowo, powiedzmy "item1", jak mogę dodać przycisk poniżej, który po kliknięciu go kopiuje "item1"Jak utworzyć przycisk "Kopiuj do schowka" w html/javascript

+3

Możliwy duplikat [Jak mogę skopiować do Schowka w JavaScript?] (Http://stackoverflow.com/questions/400212/how-do-i-copy-to- the-clipboard-in-javascript) – Pedram

+0

Jak dodać kod do istniejącego kodu, który opublikowałem? – ammartjr

+0

Potrzebuję jednego przycisku, który po kliknięciu automatycznie kopiuje, nie trzeba ponownie wpisywać w polu lub cokolwiek innego – ammartjr

Odpowiedz

22

I dodano ve trochę linii do kodu, spróbuj tego działa!

<html> 
 
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" /> 
 
<p id="message" ></p><br> 
 
<button onclick="copyToClipboard('message')">Copy</button> 
 

 
<script> 
 
function GetValue() 
 
{ 
 
    var myarray= new Array("item1","item2","item3"); 
 
    var random = myarray[Math.floor(Math.random() * myarray.length)]; 
 
    //alert(random); 
 
    document.getElementById("message").innerHTML=random; 
 
} 
 

 
function copyToClipboard(elementId) { 
 

 

 
    var aux = document.createElement("input"); 
 
    aux.setAttribute("value", document.getElementById(elementId).innerHTML); 
 
    document.body.appendChild(aux); 
 
    aux.select(); 
 
    document.execCommand("copy"); 
 

 
    document.body.removeChild(aux); 
 

 
} 
 
</script> 
 

 
</html>

0

szukasz skryptu będzie:

function GetValue() 
{ 
    var myarray = new Array("item1", "item2", "item3"); 
    var random = myarray[Math.floor(Math.random() * myarray.length)]; 
    var message = document.getElementById("message"); 
    message.value = random; 
    message.select(); 
    document.execCommand('copy'); 
} 

Element wiadomość musi być elementem wyboru, czyli wprowadzania tekstu lub textarea: <input id="message">

Powiązane problemy