Write By CS 逍遥剑仙
我的主页: http://www.csxiaoyao.com/
- GitHub: https://github.com/csxiaoyaojianxian
- Email: sunjianfeng@csxiaoyao.com
前端拾零收录日常开发中一些很常见很基础的前端操作, 省去每次 google 甚至答案错误的烦恼
github 演示地址 http://htmlpreview.github.io/?https://github.com/csxiaoyaojianxian/JavaScriptStudy/blob/master/19-前端拾零/01-checkbox&radio&select.html , 看这个在线演示可以省略以下说明
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")
- www.csxiaoyao.com
来源: https://www.qcloud.com/developer/article/1188926