如果信息存储在对象数组中,我将如何使用循环更改复选框和单选标签和值?
var products = [];//PRODUCT OBJECT ARRAY FOR DROPDOWN DATA
products[0] = { price:[8.85, 11.95,14.95,18.95]};
products[1] = { price:[8.85, 11.95,14.95,18.95]};
products[2] = { price:[7.95, 9.95,11.95,15.95]};
products[3] = { price:[9.95, 12.95,15.95,19.95]};
products[4] = { price:[9.95, 15.95,20.95,29.95]};
我有其他对象属性(想节省空间)
我只需要编写一个循环来将4个单选按钮标签和3个复选框值更改为这些价格。基于4项下拉列表
var labels = document.getElementsByName("size");
var productsList = document.getElementById("selectProduct");
for(var count = 0; count < 5; count++){
labels.innerHTML = products[productsList.selectedIndex].price[count] ;
}
alert(labels[0]);'
我知道这很糟糕我还在赚钱:( ...
HTML:
<p class="alignR">
<input type="radio" name="size" id="small" value="small"><label id="one">small</label><br>
<input type="radio" name="size" id="medium" value="medium"><label id="two">small</label><br>
<input type="radio" name="size" id="large" value="large"><label id="three">small</label><br>
<input type="radio" name="size" id="party" value="party"><label id="four">small</label><br><br>
</p>
<p class="alignL">Any extras?</p>
<form id="checkBox">
<p class="alignR">
<input type="checkbox" name="toppings" id="4" value="sauce"><label id="five">more hot sauce</label><br>
<input type="checkbox" name="toppings" id="5" value="dip"><label id="six">more hot sauce</label><br>
<input type="checkbox" name="toppings" id="6" value="veggies"><label id="seven">more hot sauce</label><br><br>
</p>
是我尝试过的......
答案 0 :(得分:0)
您需要分配到labels[count]
。此外,您的for
循环重复次数过多 - 只有4个单选按钮,但您重复了5次。最好从数据中计算重复次数,而不是将其硬编码到循环中(参见我的labelCount
变量)。
另一个问题是labels
不包含label
元素,它包含input
元素,因此您要分配错误的元素“innerHTML
。我在标签上添加了一个类,然后使用它。
var products = [ //PRODUCT OBJECT ARRAY FOR DROPDOWN DATA
{
price: [8.85, 11.95, 14.95, 18.95]
}, {
price: [8.85, 11.95, 14.95, 18.95]
}, {
price: [7.95, 9.95, 11.95, 15.95]
}, {
price: [9.95, 12.95, 15.95, 19.95]
}, {
price: [9.95, 15.95, 20.95, 29.95]
}
];
var labels = document.getElementsByClassName("sizeLabel");
var labelCount = labels.length;
var productsList = document.getElementById("selectProduct");
productsList.addEventListener("change", function() {
for (var count = 0; count < labelCount; count++) {
labels[count].innerHTML = products[productsList.selectedIndex].price[count];
}
});
<select id="selectProduct">
<option>Product 1</option>
<option>Product 2</option>
<option>Product 3</option>
<option>Product 4</option>
<option>Product 5</option>
</select>
<p class="alignR">
<input type="radio" name="size" id="small" value="small">
<label class="sizeLabel" id="one">small</label>
<br>
<input type="radio" name="size" id="medium" value="medium">
<label class="sizeLabel" id="two">small</label>
<br>
<input type="radio" name="size" id="large" value="large">
<label class="sizeLabel" id="three">small</label>
<br>
<input type="radio" name="size" id="party" value="party">
<label class="sizeLabel" id="four">small</label>
<br>
<br>
</p>