前端拾零01—checkbox&radio&select总结
Write By CS逍遥剑仙
我的主页: csxiaoyao.com
GitHub: github.com/csxiaoyaojianxian
Email: sunjianfeng@csxiaoyao.com
QQ: 1724338257
前端拾零收录日常开发中一些很常见很基础的前端操作,省去每次google甚至答案错误的烦恼
github演示地址,看这个在线演示可以省略以下说明
1. checkbox
设置选中
// js设置check1选中 document.getElementById('check1').checked = true // jq设置check2不选中 $("#check2").prop("checked", false)
判断选中状态
// js判断id=check1状态 document.getElementById("check1").checked // jq判断id=check2状态 $("#check2").prop('checked')
获取选中元素
var selector = "input[type=checkbox][name='cs-checkbox']:checked" // js document.querySelectorAll(selector) // jq $(selector)
2. radio
设置选中
// js设置value=1选中 document.querySelector("input[type='radio'][name='cs-radio'][value='1']").checked = true // jq prop设置value=2不选中 $("input[type=radio][name='cs-radio'][value=2]").prop("checked", false) // jq attr设置value=3选中 $("input[type=radio][name='cs-radio'][value=3]").attr("checked",true)
判断选中状态
// js判断value=1状态 document.querySelector("input[type='radio'][name='cs-radio'][value='1']").checked // jq判断value=2状态 $("input[type=radio][name=cs-radio][value=2]").prop('checked')
获取选中元素
var selector = "input[type='radio'][name='cs-radio']:checked" // js document.querySelector(selector) // jq $(selector)
3. select
设置选中
// js选择value="csxiaoyao" document.querySelector("select.select option[value='csxiaoyao']").selected = true // jq选择value="sunshine" $("select.select option[value='sunshine']").attr("selected", true)
判断选中状态
// js判断第2个元素是否选中 document.querySelector("select.select").options[1].selected // js判断csxiaoyao是否选中 document.querySelector("select.select option[value='csxiaoyao']").selected // jq判断sunshine是否选中 $("select.select option[value='sunshine']").prop("selected")
获取选中元素和索引
// js var dom = document.querySelector("select.select") var index1 = dom.selectedIndex result = dom.options[index1] // jq $("select.select").val() $("select.select").find('option:selected') $("select.select option:selected") $("select.select option:last")