这里为您讲解一下“javascript实现点击单选按钮链接转向对应网址的方法”的攻略:
这里为您讲解一下“javascript实现点击单选按钮链接转向对应网址的方法”的攻略:
1. HTML 结构
首先,需要在 HTML 中添加单选按钮和链接的结构,例如:
<input type="radio" name="link" value="https://www.example.com/1"/> Example 1<br>
<input type="radio" name="link" value="https://www.example.com/2"/> Example 2<br>
<input type="radio" name="link" value="https://www.example.com/3"/> Example 3<br>
<a href="#" id="myLink">Go to link</a>
2. Javascript 实现
接着,在 JavaScript 中添加点击事件,根据选中的单选按钮的值修改链接的 href 属性,并跳转到对应网址,例如:
let radios = document.getElementsByName('link');
let link = document.getElementById('myLink');
for (let i = 0; i < radios.length; i++) {
radios[i].addEventListener('click', function() {
link.href = this.value;
});
}
link.addEventListener('click', function(e) {
e.preventDefault();
window.location.href = link.href;
});
以上代码中,通过 getElementsByName 获取单选按钮组,遍历每个单选按钮,并为其添加点击事件。在事件处理程序中,将选中单选按钮的值设置为链接的 href 属性。每个单选按钮的值,分别对应了不同的网址。
同时,为链接也添加了点击事件,在事件处理程序中,首先阻止默认的链接跳转行为,然后使用 window.location.href 跳转到设置的网址。
3. 示例
这里提供两个示例:
- 当选中“Example 1”单选按钮时,点击链接跳转到
https://www.example.com/1:
<input type="radio" name="link" value="https://www.example.com/1" checked/> Example 1<br>
<input type="radio" name="link" value="https://www.example.com/2"/> Example 2<br>
<input type="radio" name="link" value="https://www.example.com/3"/> Example 3<br>
<a href="#" id="myLink">Go to link</a>
- 当选中“Example 2”单选按钮时,点击链接跳转到
https://www.example.com/2:
<input type="radio" name="link" value="https://www.example.com/1"/> Example 1<br>
<input type="radio" name="link" value="https://www.example.com/2" checked/> Example 2<br>
<input type="radio" name="link" value="https://www.example.com/3"/> Example 3<br>
<a href="#" id="myLink">Go to link</a>
以上就是“javascript实现点击单选按钮链接转向对应网址的方法”的完整攻略,希望能对您有所帮助。
本文标题为:javascript实现点击单选按钮链接转向对应网址的方法
基础教程推荐
- Entity Framework Code First数据库连接 转载 https://www.cnblogs.com/libingql/p/3351275.html 2023-10-25
- 在实战中可能碰到的几种ajax请求方法详解 2023-01-31
- CSS隐藏页面元素的5种方法 2023-12-20
- document.execCommand()的用法小结 2023-12-15
- 关于 extjs:Resolving Dirty Flag in Ext.grid.Panel cell 2022-09-15
- JS判断传入函数的参数是否为空(函数参数是否传递) 2023-08-08
- 利用递增的数字返回循环渐变的颜色的js代码 2023-12-15
- 基于Html+CSS+JS实现手动放烟花效果 2023-12-13
- vue中面包屑的封装 2023-10-08
- HTML学习笔记(第五天) 2023-10-26
