我为一个表单编写了一些逻辑,其中第二个下拉列表中的可用项根据第一个选择进行更改。
克隆下拉菜单,允许用户在需要时使用多个。
如果原始下拉列表中有任何更改,克隆的下拉列表也会更改。克隆选项中的第二个字段不响应第一个字段中的更改事件。
我希望每个克隆的字段集的行为独立于其他字段集。这是一个小提琴:http://jsfiddle.net/HchH8/
为什么会发生这种情况?我尝试使用克隆(真的,真的)深度复制,它没有工作。我在SO上搜索过类似的问题,我只是不能把我的头绕在我找到的答案上。我是新手。有人能帮帮我吗?
jQuery
prods = {
Cookware: ["- Select -", "Round French Oven", "Oval French Oven", "Braiser", "Skillet", "Fry Pan", "Grill Pan", "Saute Pan", "Saucepan", "Saucier", "Griddle", "Roaster", "Stockpot", "Speciality Cookware", "Other"],
Bakeware: ["- Select -", "Covered Casserole", "Baking Dish", "Stoneware Gratin", "Speciality Bakeware", "Individual Bakeware", "Metal Bakeware", "Other"],
KitchenTools: ["- Select -", "Utensils", "Kitchen Accessories", "Cutlery", "Wine Tools", "Textiles", "Other"],
DineEntertain: ["- Select -", "Dinnerware", "Serveware", "Tabletop Accessories", "Glassware", "Kettles", "Tea Collection", "Café Collection", "Other"]
};
var category = $('select[name^="Product_category"]');
var productType = $('select[name^="Product_type"]');
$('.prod-info').live("change", function () {
var catSelected = $(this).val();
$(this).parent("li").next("li.subCats").fadeIn('fast'); /*Fades in next option once selection has been made*/
if($(this).is(category)) {
$('select[name^="Product_type"]').empty();
$('.product-size, .product-color').prop('selectedIndex',0);
$.each(prods[catSelected], function (key, value) {
$('select[name^="Product_type"]')
.append($("<option></option>")
.attr("value", value)
.attr("name", value)
.text(value));
});
}
if($(this).is(productType)) {
$('.product-size, .product-color').prop('selectedIndex',0);
}
});
var otherSelect = $('select');
var select = this.value;
otherSelect.change(function () {
if ($(this).val() == 'Other') {
$(this).next('.other').show();
}
else $(this).next('.other').hide();
});
for (var i = 2; i < 6; i++) { // add counts in a for loop
$('select[name="numProd"]').append('<option value=' + i + '>' + i + '</option>');
}
$.fn.duplicate = function(count, cloneEvents) {
var tmp = [];
for (var i = 0; i < count; i++) {
$.merge(tmp, this.clone(cloneEvents, true, true).get());
}
return this.pushStack(tmp);
};
//SELECT CHANGE FUNCTION (on change get value and clone)
$('select[name="numProd"]').change(function(){ // on change...
var numOfClones = $(this).val() -1; // get value...
var cntr = 2;
$('#addProds').empty(); // empty holder if there are some old clones
$('.prodDetails').duplicate(numOfClones).appendTo('#addProds').each(function() {
$(this).find("select").each(function() {
if (this.name) {
this.name += cntr;
}
if (this.id) {
this.id += cntr;
}
});
++cntr;
});
// duplicate; fill holder with new clones; the class 'new' is just for styling
});