[英]How do I add a second link to this java script radio selection?
I cant figure out how to insert the second link. 我不知道如何插入第二个链接。 I'd like each radio button to direct to a different link.
我希望每个单选按钮都指向不同的链接。
<script> function myFunction() { if(document.getElementById('slide1').checked) { document.getElementById('myLink').href = "https://www.nationsprint.com/clients/ccpopv2/catalog.cgi"; } } </script>
<input checked="" type="radio" name="slider" id="slide1"> <input type="radio" name="slider" id="slide2" > <a href="" onclick='myFunction()' id="myLink">MyLink</a>
Radio buttons support different values. 单选按钮支持不同的值。 You can use this to set them the url you want them to redirect to.
您可以使用它来设置他们想要他们重定向到的URL。
<input type="radio" name="slider" id="slide2" value="https://www.nationsprint.com/clients/ccpopv2/catalog.cgi">
Then, you can use document.querySelector to get the selected radio. 然后,您可以使用document.querySelector获取选定的单选。
var link = document.querySelector('input[name="slider"]:checked').value
Here's a snippet showing how it works: 这是显示其工作原理的代码段:
function myFunction() { var link = document.querySelector('input[name="slider"]:checked').value document.getElementById('myLink').href = link; }
<input checked="checked" type="radio" name="slider" id="slide1" value="https://stackoverflow.com/"> <input type="radio" name="slider" id="slide2" value="https://www.nationsprint.com/clients/ccpopv2/catalog.cgi"> <a href="" onclick='myFunction()' id="myLink">MyLink</a>
You can't add multiple href
s to one element. 您不能将多个
href
添加到一个元素。 If I understand you correctly, you want to change href
based on selected radio input. 如果我对您的理解正确,则希望根据所选的单选输入更改
href
。 Here it is: 这里是:
function myFunction() { if (document.getElementById('slide1').checked) { document.getElementById('myLink').href = "https://www.nationsprint.com/clients/ccpopv2/catalog.cgi"; } else if (document.getElementById('slide2').checked) { document.getElementById('myLink').href = "https://stackoverflow.com/"; } alert("Current 'href' is: " + document.getElementById('myLink').href); }
<input checked="" type="radio" name="slider" id="slide1"> <input type="radio" name="slider" id="slide2" > <a href="" onclick='myFunction()' id="myLink">MyLink</a>
You should set the href as 'javascript:void(0)',to prevent the tag's default action. 您应将href设置为“ javascript:void(0)”,以防止标记的默认操作。
function myFunction() { var slide1=document.getElementById('slide1'); var slide2=document.getElementById('slide2'); var myLink=document.getElementById('myLink'); if(slide1.checked) { myLink.href = "https://www.nationsprint.com/clients/ccpopv2/catalog.cgi"; } if(slide2.checked) { myLink.href = "https://stackoverflow.com/"; } }
<input checked="" type="radio" name="slider" id="slide1"> <input type="radio" name="slider" id="slide2" > <a href="javascript:void(0)" onclick='myFunction()' id="myLink" >MyLink</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.