jQuery change事件触发append未正确生成对应数量输入框问题
问题根因
你代码里的多值匹配条件存在语法错误,bettype == "treble" || "trixie" || "patent"的判断逻辑不符合JS语法规则:
- JS会优先计算
bettype == "treble"的结果,若为false,后续的"trixie"是非空字符串,属于布尔真值,因此整个条件会永远返回true - 所有
single、double之外的选项都会优先命中这个条件分支,永远只生成3个输入框,根本不会走到后续fourfold及更高阶的判断逻辑里
修复方案
把所有多条件匹配的语句补全完整的判断表达式,同时可以将重复的移除操作、输入框生成逻辑简化,参考代码如下:
$("#bettype").change(function() { var bettype = $(this).children("option:selected").val(); $(".removethis").remove(); // 统一提前移除旧输入框,避免每个分支重复写 let count = 0; // 先匹配对应选项的输入框数量 if (bettype == "single") { count = 1; } else if (bettype == "double") { count = 2; } else if (bettype == "treble" || bettype == "trixie" || bettype == "patent") { count = 3; } else if (bettype == "fourfold" || bettype == "yankee" || bettype == "lucky15") { count = 4; } else if (bettype == "fivefold") { count = 5; } else if (bettype == "sixfold") { count = 6; } else if (bettype == "sevenfold") { count = 7; } else if (bettype == "eightfold") { count = 8; } // 统一生成对应数量的输入框 if (count === 1) { $("#selections").append($("<input type='text' value='Single' class='removethis'/>")); } else { for(let i=1; i<=count; i++){ $("#selections").append($(`<input type='text' value='Selection ${i}' class='removethis'/>`)); } } });
内容的提问来源于stack exchange,提问作者ChrisYates
相关产品推荐
相关产品推荐

