用jquery判断设置单选复选框时,有时会有些迷糊,今天总结下。
<dl> <dt>单选框</dt> <dd> <label><input type="radio" name="gender" value="男" />男</label> <label><input type="radio" name="gender" value="女" />女</label> </dd> <dt>复选框</dt> <dd> <label><input type="checkbox" name="fun" value="篮球" />篮球</label> <label><input type="checkbox" name="fun" value="足球" />足球</label> <label><input type="checkbox" name="fun" value="乒乓球" />乒乓球</label> </dd> </dl> <button onclick="setValue()">原生js设置值</button> <button onclick="getValue()">原生js取值</button> <button onclick="setVal()">jquery设置值</button> <button onclick="getVal()">jquery取值</button> <!-- <script src="./plugins/jquery/jquery-3.6.0.min.js"></script> --> <script src="./plugins/jquery/jquery-1.12.4.min.js"></script> <script> function setValue() { document.querySelectorAll('input[name="gender"]').forEach((elem, index) => { if (index < 1) { elem.checked = true; } else { elem.checked = false; } }); document.querySelectorAll('input[name="fun"]').forEach((elem, index) => { if (index < 1) { elem.checked = true; } else { elem.checked = false; } }); } function getValue() { let gender = ""; document.querySelectorAll('input[name="gender"]').forEach((elem) => { if (elem.checked) gender = elem.value; }); const fun = []; document.querySelectorAll('input[name="fun"]').forEach((elem) => { if (elem.checked) fun.push(elem.value); }); console.log("原生js checked属性判断", gender, fun); } function setVal() { $('input[name="gender"]').each((index, elem) => { //不生效 // if (index < 1) { // $(elem).attr("checked", true); // } else { // $(elem).attr("checked", false); // } //生效 if (index < 1) { $(elem).prop("checked", true); } else { $(elem).prop("checked", false); } }); $('input[name="fun"]').each((index, elem) => { //不生效 // if (index < 1) { // $(elem).attr("checked", true); // } else { // $(elem).attr("checked", false); // } //生效 if (index < 1) { $(elem).prop("checked", true); } else { $(elem).prop("checked", false); } }); } function getVal() { let gender1 = ""; let gender2 = ""; let gender3 = ""; $('input[name="gender"]').each((index, elem) => { if ($(elem).is(":checked")) gender1 = elem.value; if ($(elem).attr("checked")) gender2 = elem.value; if ($(elem).prop("checked")) gender3 = elem.value; }); const fun1 = []; const fun2 = []; const fun3 = []; $('input[name="fun"]').each((index, elem) => { if ($(elem).is(":checked")) fun1.push(elem.value); if ($(elem).attr("checked")) fun2.push(elem.value); if ($(elem).prop("checked")) fun3.push(elem.value); }); console.log('jquery is(":checked")方法判断', gender1, fun1); console.log('jquery attr("checked")方法判断', gender2, fun2); console.log('jquery prop("checked")方法判断', gender3, fun3); } </script>
才发现记忆总是有些偏差,偏偏记得attr方法是可用的。而现实就是attr方法是不可用的那个。
标签:jquery,index,checked,attr,elem,复选框,单选,input From: https://www.cnblogs.com/caroline2016/p/17930987.html