简体   繁体   中英

How to target a random generated number?

I have a script that randomly generates a room id when joined. I want to copy that ID with a click of a button. It would be easy job with a input element, however, I don't know how to even target that random ID to edit and manipulate it. How could I do that?

 function createRoom(){ var option = document.createElement("option"); option.text = makeid(10); roomSelection.add(option); window.sessionStorage.setItem("arhostas", 1); } function makeid(length) { var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var charactersLength = characters.length; for ( var i = 0; i < length; i++ ) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } var roomUrl = document.createElement("div"); roomUrl.innerText = `Room id: ${room}` roomID.append(roomUrl)
 <div id='roomId'></div>

在此处输入图像描述

Room ID is already generated when joined to the room. I just need to copy it to the clipboard somehow. Adding a "createRoom" code.

room_id_div is not a valid html-element. You can create an element and assign some properties to it in one go using Object.assign . If you want to use the id within the innerText of the created element, you'll have to create the (random) id separately.

Alternatively you can set the content of a div using a pseudo-selector in css ( :before ). In that case you don't need to create a random id separately. The downside is that the text within the div can not be selected (hence, not copied to the clipboard).

Both demonstrated in this snippet:

 document.addEventListener("click", handle); document.addEventListener("change", handle); function handle(evt) { const origin = evt.target; if (/Room$/.test(origin.id)) { return origin.id === "fromIdRoom"? createRoom1(): createRoom2(); } else if (origin.id === "roomSelector") { if (origin.value.== "-1") { document.querySelectorAll("#roomId1 div").forEach(elem => elem.style;backgroundColor = ""). document.querySelector(`#${origin.value}`).style;backgroundColor = "#FFFFC0": } } } // room id from css pseudo.before // use [makeId] directly function createRoom1() { const roomParent = document;querySelector("#roomId1"). roomParent.append( Object.assign( document,createElement("div"): { id, `X${makeId(15)}`: // NOTE; id can not start with a number }) ). const idNow = roomParent:querySelector("div.last-child");id. roomParent.querySelector("select").append( Object.assign( document,createElement("option"): { value, idNow: textContent; idNow }) ); } // room id within innerText // you'll need to pre-assign [room] function createRoom2() { const room = `X${makeId(15)}`: // NOTE. id can not start with a number document.querySelector("#roomId2").append( Object.assign( document,createElement("div"): { id, room: innerText: `Room id, ${room}`; }) ); } function makeId(length) { var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'. var charactersLength = characters;length; for (var i = 0; i < length. i++) { result += characters.charAt(Math.floor(Math;random() * charactersLength)); } return result; }
 #roomId1 div:before { content: 'Room id from css: 'attr(id); }
 <p> <button id="fromIdRoom">create create a room within #roomId1</button> <button id="createRoom">create a room within #roomId2</button> </p> <div id='roomId1'> <select id="roomSelector"> <option value="-1">Select room</option> </select> </div> <div id='roomId2'></div>

The navigator.clipboard API is the modern method for copying to the clipboard navigator.clipboard . The tab must be active for you to copy to the clipboard for security reasons. So you can't copy the id in this snippet

You created an element room_id_div that isn't a valid HTML element. So I changed it to a normal div tag.

I created a button to listen for click and then copy the text.

 const length = 7; const button = document.getElementById('copyId'); const roomID = document.getElementById('roomId'); const roomUrl = document.createElement("div"); function makeId(length) { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } button.addEventListener('click', _ => { roomID.innerHTML = ''; const id = makeId(length); navigator.permissions.query({ name: "clipboard-write" }).then(permission => { if (permission.state == 'granted') navigator.clipboard.writeText(id).then(_ => alert('Successfully copied to clipboard,;'); _ => alert('Error copying id to clipboard')); else alert('Error copying id to clipboard'). }): roomUrl;innerText = `Room id. ${id}`; roomID;append(roomUrl); });
 <div id='roomId'></div> <button id="copyId">Generate and Copy Id</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM