Javascript 使用switch语句选择radiobutton时更改href值

Javascript 使用switch语句选择radiobutton时更改href值,javascript,jquery,input,switch-statement,href,Javascript,Jquery,Input,Switch Statement,Href,根据选择的radiobutton,尝试更改语句中的href引用 <ul class="size_selector"> <li class="top"><input type="radio" class="radioselect" name="id" id="test1" value="test1" /><label for="test1">1</label></li&

根据选择的radiobutton,尝试更改语句中的href引用

        <ul class="size_selector">
                        <li class="top"><input type="radio" class="radioselect" name="id" id="test1" value="test1" /><label for="test1">1</label></li>
                        <li class="top"><input type="radio" class="radioselect" name="id" id="test2" value="test2"/> <label for="test2">2</label></li>
                        <li class="top"><input type="radio" class="radioselect" name="id" id="test3" value="test3"/> <label for="test3">3</label></li>
                        <li class="top"><input type="radio" class="radioselect" name="id" id="test4" value="test4"/> <label for="test4">4</label></li>
        </ul>
<a id="shopCart" href="#">
    Take me to your leader
</a>

您正在使用JQuery,但没有链接到它。
设置->JavaScript

添加此链接。

您只需使用
$(“#购物车”).attr(“href”http://yahoo.com");
等等。

如果将输入值更改为[0,1,2,3],则可以将链接放入一个数组中,同时去掉switch语句并简化代码

HTML 我使用该值指定要替换链接的数组元素


这比您的代码更枯燥,冗余更少。

您的意思是
document.getElementById(“shopCart”).href=”http://yahoo.com";
可以替换为
$(“#购物车”).attr(“href”,”http://yahoo.com");准确地说:)确保您正在使用jQuery
$("input[type='radio']").change(function(){

switch($(this).val()) {
  case "test1" :
    document.getElementById("shopCart").href="http://yahoo.com"; 
    break;
  case "test2" :
    document.getElementById("shopCart").href="http://bing.com"; 
    break;
  case "test3" :
    document.getElementById("shopCart").href="http://google.com"; 
     break;
  case "test4" :    document.getElementById("shopCart").href="http://stackoverflow.com";
    break;
  };

});
<ul class="size_selector">
    <li class="top"><input type="radio" class="radioselect" name="id" id="test1" value="0" /><label for="test1">1</label></li>
    <li class="top"><input type="radio" class="radioselect" name="id" id="test2" value="1"/> <label for="test2">2</label></li>
    <li class="top"><input type="radio" class="radioselect" name="id" id="test3" value="2"/> <label for="test3">3</label></li>
    <li class="top"><input type="radio" class="radioselect" name="id" id="test4" value="3"/> <label for="test4">4</label></li>
</ul>
<a id="shopCart" href="#">
    Take me to your leader
</a>
var links = ["http://yahoo.com", "http://bing.com", "http://google.com", "http://stackoverflow.com"]

$("input[type='radio']").change(function(){
    $("#shopCart").attr("href", links[$(this).val()]);
});