当前位置:首页 > JavaScript

js 实现单选

2026-04-07 02:59:25JavaScript

实现单选功能的 JavaScript 方法

使用 HTML 和 JavaScript 原生实现

创建一组单选按钮,通过 JavaScript 监听点击事件并更新选中状态。

<input type="radio" name="option" value="1" id="option1">
<label for="option1">选项1</label>
<input type="radio" name="option" value="2" id="option2">
<label for="option2">选项2</label>
<input type="radio" name="option" value="3" id="option3">
<label for="option3">选项3</label>

<script>
  const radios = document.querySelectorAll('input[name="option"]');
  radios.forEach(radio => {
    radio.addEventListener('change', function() {
      if (this.checked) {
        console.log('选中值:', this.value);
      }
    });
  });
</script>

使用事件委托优化性能

对于大量单选按钮,使用事件委托减少事件监听器数量。

<div id="radioGroup">
  <input type="radio" name="option" value="1" id="option1">
  <label for="option1">选项1</label>
  <!-- 更多选项... -->
</div>

<script>
  document.getElementById('radioGroup').addEventListener('change', function(e) {
    if (e.target.type === 'radio') {
      console.log('选中值:', e.target.value);
    }
  });
</script>

动态生成单选按钮

通过 JavaScript 动态创建单选按钮组。

const options = ['红色', '绿色', '蓝色'];
const container = document.getElementById('container');

options.forEach((text, i) => {
  const radio = document.createElement('input');
  radio.type = 'radio';
  radio.name = 'color';
  radio.value = text;
  radio.id = 'color' + i;

  const label = document.createElement('label');
  label.htmlFor = 'color' + i;
  label.textContent = text;

  container.appendChild(radio);
  container.appendChild(label);
});

获取当前选中值

通过选择器获取当前选中的单选按钮值。

function getSelectedValue(name) {
  const selected = document.querySelector(`input[name="${name}"]:checked`);
  return selected ? selected.value : null;
}

// 使用示例
console.log(getSelectedValue('color'));

设置默认选中项

通过 JavaScript 设置默认选中的单选按钮。

document.querySelector('input[value="绿色"]').checked = true;

自定义单选按钮样式

结合 CSS 隐藏原生单选按钮,实现自定义样式。

.custom-radio {
  display: none;
}
.custom-radio + label {
  display: inline-block;
  padding: 5px 10px;
  border: 1px solid #ccc;
  cursor: pointer;
}
.custom-radio:checked + label {
  background-color: #007bff;
  color: white;
}
<input type="radio" class="custom-radio" id="custom1" name="custom">
<label for="custom1">自定义选项1</label>

使用框架实现(如 jQuery)

使用 jQuery 简化单选按钮操作。

$('input[name="option"]').change(function() {
  console.log('选中值:', $(this).val());
});

// 设置选中
$('input[name="option"][value="2"]').prop('checked', true);

表单提交处理

在表单提交时获取单选按钮的值。

js 实现单选

<form id="myForm">
  <input type="radio" name="gender" value="male"> Male
  <input type="radio" name="gender" value="female"> Female
  <button type="submit">提交</button>
</form>

<script>
  document.getElementById('myForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    console.log('性别:', formData.get('gender'));
  });
</script>

标签: 单选js
分享给朋友:

相关文章

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…

js 实现mvc

js 实现mvc

MVC 模式简介 MVC(Model-View-Controller)是一种软件设计模式,将应用程序分为三个核心组件:模型(Model)处理数据和业务逻辑,视图(View)负责展示数据,控制器(Con…

vue实现checkbox单选

vue实现checkbox单选

Vue实现Checkbox单选功能 在Vue中实现Checkbox单选功能,可以通过以下几种方法: 方法一:使用v-model绑定单个变量 通过将多个Checkbox绑定到同一个变量,利用v-mo…

vue 实现单选全选

vue 实现单选全选

实现单选和全选功能 在Vue中实现单选和全选功能,可以通过v-model指令绑定数据,结合计算属性和方法来实现交互逻辑。以下是一个完整的实现方案。 基础数据结构 定义列表数据,每个数据项包含选中状态…