如何基于单选按钮选择创建动态导航

时间:2018-04-06 20:31:51

标签: javascript php jquery

当访问者选择目的地(例如,火星)并点击按钮时,他们会转到相关页面。

有更好的方法吗?

示例:

按钮标签:

<label class="destinationlabel">
<input type="radio" class="field-radio" name="destiny" value="Mars">
<span class="MarsSpanClass" title="Mars">Mars</span>
</label>

<label class="destinationlabel">
<input type="radio" class="field-radio" name="moon" value="Moon">
<span class="MoonSpanClass" title="Mars">Moon</span>
</label>

按钮DIV:

 <div class="box">
  <button id="gobutton" class="buttonclass">
    <i class="buttontextclass"></i>
    Go
  </button>
</div>

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

每个单选按钮都可以在value属性中存储它对应的位置。然后,当单击该按钮时,它会读取所选单选按钮的value属性,并将window.location更改为该URL。

您的HTML可以简化,因为label元素可以完成您当前使用span元素的工作。

document.getElementById("gobutton").addEventListener("click", function(){
  // Get the value of the checked radio button
  var newLocation = document.querySelector("input[name='destiny']:checked").value;
  alert("Redirecting to: " + newLocation);  // Just for testing
  window.location = newLocation;            // Redirect to the new location
});;
<input type="radio" class="field-radio" name="destiny" id="mars" value="mars.html">
<label for="mars" class="destinylabel">Mars</label>

<input type="radio" class="field-radio" name="destiny" id="moon" value="moon.html">
<label for="moon" class="destinylabel">Moon</label>


 <div class="box">
  <button id="gobutton" class="buttonclass">
    <i class="buttontextclass"></i>
    Go
  </button>
</div>