[英]Splice function in javascript not working properly
單擊上的按鈕應生成單選按鈕,一次一個,但我對應該堅持使用單選按鈕的文本節點有疑問。 這是代碼的一部分:
var array = [];
items = document.getElementById("items").value.split(",");
for (var i = 0; i < items.length; i++) {
array.push(items[i]);
}
type = document.getElementById("type");
container = document.getElementById("container");
if (type.value == "radio") {
radio = document.createElement("input");
radio.setAttribute("type", "radio");
for (var i = 0; i < array.length; i++) {
text = document.createTextNode(array[0]);
container.appendChild(text);
container.appendChild(radio);
array.splice(0,1);
}
}
所以這就是結果,但我希望第一個單選按鈕的值為“1”,第二個為“2”等。
開始步驟你不需要array
的items
陣列已經包含文本輸入你想要的元素
甲LSO無需切片/接續任何陣列
Ÿ我們的問題是,你必須創建為每一個元素另一種獨特的無線電元素,所以你沒被追加相同的無線電元素很多次,這導致加一次的單選按鈕是什么
所以你必須把radio = document.createElement("input"); radio.setAttribute("type", "radio");
radio = document.createElement("input"); radio.setAttribute("type", "radio");
在 for 循環內。 . . . 😘😘
function Z() { items = document.getElementById('items').value.split(","); type = document.getElementById("type"); container = document.getElementById("container"); container.innerHTML = ""; if (type.value == "radio") { for (var i = 0; i < items.length; i++) { text = document.createTextNode(items[i]); radio = document.createElement("input"); radio.setAttribute("type", "radio"); container.appendChild(text); container.appendChild(radio); } } }
<input onkeyup="Z()" id="items"> type: <select id="type"> <option value="radio">Radio</option> <option value="checkbox">Text</option> </select> <div id='container'></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.