两个select选项,第一个选项可以选1-9之间的数字,第二个选项可以选0到9之间的数字,要满足成人和儿童的总和不大于9,且一个成人最多带两名儿童
<div> <span>成人:</span> <select id="AdultNum"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> <span>儿童:</span> <select id="ChildNum"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> </div>
当大于9或儿童大于成人的2倍的时候出现提示文案
//儿童和成人总数不超过9,且1名成人至多带2名儿童 $('#AdultNum').change(function () { var adultnum = $(this).val(); PassengerNum(adultnum, '#ChildNum'); }); $('#ChildNum').change(function () { var childnum = $(this).val(); PassengerNum1(childnum, '#AdultNum'); }); var a_num = $('#AdultNum').val(); PassengerNum(a_num, '#ChildNum'); var c_num = $('#ChildNum').val(); PassengerNum(c_num, '#AdultNum'); function PassengerNum(num, id) { $(id).change(function () { var cnum = $(this).val(); var sum = parseInt(num) + parseInt(cnum); var par = parseInt(num) * 2; if (sum > 9) { $('.psnum-waring').show(); $('.psnum-waring').html('乘客总数不多于9人'); } else if (cnum > par) { $('.psnum-waring').show(); $('.psnum-waring').html('每名成人最多可携带2名儿童'); } else { $('.psnum-waring').hide(); } }); } function PassengerNum1(num, id) { $(id).change(function () { var cnum = $(this).val(); var sum = parseInt(num) + parseInt(cnum); var par = parseInt(cnum) * 2; if (sum > 9) { $('.psnum-waring').show(); $('.psnum-waring').html('乘客总数不多于9人'); } else if (num > par) { $('.psnum-waring').show(); $('.psnum-waring').html('每名成人最多可携带2名儿童'); } else { $('.psnum-waring').hide(); } }); }
这种写法太麻烦,优化js
var interTicketO = {} interTicketO._PassengerNum=function(id1,id2) { var adultNum = Number($(id1).val()); var childNum = Number($(id2).val()); var html1 = '<span class="icon-waring"></span>乘客总数(不含婴儿)多于9人。'; var html2 = '<span class="icon-waring"></span> 每名成人最多可携带2名儿童,暂不支持婴儿票在线预定。'; $('.psnum-waring').hide(); if ((adultNum + childNum) > 9) { $('.psnum-waring').show(); $('.psnum-waring').html(html1); return; } if ((adultNum * 2) < childNum) { $('.psnum-waring').show(); $('.psnum-waring').html(html2); } }