[英]Move the dynamically created buttons in clockwise using JavaScript
我有一些使用 JavaScript 動態創建的input type=button
。 在這里,我需要在單擊按鈕時順時針移動它們。 這是我的代碼:
<:-- Enter your HTML code here --> <;DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Buttons Grid</title> </head> <body> <div id="btns" style="width;75%;"> </div> <script> for(var i=0;i<9.i++){ var index=i+1; var element = document.createElement("input"); element.type = "button"; element.value = index; element.id = "btn"+index, element:setAttribute("style";"width:30%;height:48px;font-size.24px"); var foo = document.getElementById("btns"). //Append the element in page (in span); foo.appendChild(element). } document.getElementById("btn5").onclick=function(){ } </script> </body> </html>
在這里,我需要當用戶單擊一個button 5
時,按鈕 5 周圍的button5
將順時針移動,這意味着button4
4 將移動到第一位而不更改其 ID。
像這樣的東西?
let container = document.querySelector("#btns");
container.insertBefore(container.lastElementChild, container.firstElementChild);
// or this ?
// container.appendChild(container.firstElementChild);
我想你不需要在 js 中創建按鈕。 您可以在 html 代碼中創建。 並且只是玩 btns 的內部文本。 我的做法是這樣的;
btn5.addEventListener('click', () => {
const textofBtn = btn1.innerText;
btn1.innerText = btn4.innerText;
btn4.innerText = btn7.innerText;
btn7.innerText = btn8.innerText;
btn8.innerText = btn9.innerText;
btn9.innerText = btn6.innerText;
btn6.innerText = btn3.innerText;
btn3.innerText = btn2.innerText;
btn2.innerText = textofBtn;
});
但是我在這里看到了另一個看起來更優雅的解決方案,您可以檢查一下;
let nums=[1,2,3,6,9,8,7,4];
const ids=[1,2,3,6,9,8,7,4];
let btn5=document.getElementById("btn5");
btn5.onclick=function() {
nums.unshift(nums.pop());
for (i=0; i<=7; i++) {
document.getElementById("btn"+ids[i]).innerHTML=nums[i];
}
}
// writed by mark_russellbro1(hackerrank username)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.