如何定位随机生成的数字?

How to target a random generated number?

我有一个脚本,可以在加入时随机生成一个房间 ID。我想通过单击按钮复制该 ID。使用输入元素很容易,但是,我什至不知道如何定位该随机 ID 来编辑和操作它。我该怎么做?

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>

加入房间时已经生成房间 ID。我只需要以某种方式将它复制到剪贴板。添加“createRoom”代码。

room_id_div 不是有效的 html 元素。您可以使用 Object.assign 一次性创建一个元素并为其分配一些属性。如果您想在已创建元素的 innerText 中使用 id,则必须单独创建(随机)id。

或者,您可以使用 css (:before) 中的伪选择器设置 div 的内容。在这种情况下,您不需要单独创建一个随机 ID。缺点是无法选择 div 中的文本(因此无法复制到剪贴板)。

两者都在此代码段中进行了演示:

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>

navigator.clipboard API 是复制到剪贴板的现代方法 navigator.clipboard。出于安全原因,该选项卡必须处于活动状态才能复制到剪贴板。所以你不能复制这段代码中的id

您创建的元素 room_id_div 不是有效的 HTML 元素。所以我把它改成普通的 div 标签。

我创建了一个 button 来监听点击然后复制文本。

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>