簡體   English   中英

使用javascript在單選按鈕上加載URL

[英]Load URL on radio button select using javascript

我正在使用此HTML和Javascript片段在有人更改下拉列表時重新加載頁面...

  <select id="dropdown">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>

   var orderby = jQuery('#dropdown');
        var str;
        orderby.change(function(){
        str = jQuery(this).val();
        window.location.href = "http://www.example.com?variable="+str;
    });

現在我試圖改變它,以便它適用於單選按鈕,我的HTML看起來像......

<input type="radio" id="1" value="1"> 1
<input type="radio" id="2" value="2"> 2
<input type="radio" id="3" value="3"> 3

這是三個單獨的項目,所以我無法弄清楚如何修改我的js片段兼容,任何人都可以幫忙嗎?

HTML:

<input type="radio" name="myradio" id="1" class="myradio" value="1"> 1
<input type="radio" name="myradio" id="2" class="myradio" value="2"> 2
<input type="radio" name="myradio" id="3" class="myradio" value="3"> 3

jQuery的:

$(function() {
    $('.myradio:not(:checked)').on('change', function() {
        window.location.href = "http://www.example.com?variable=" + this.value;
    });
});

概念驗證

  $(function() { $('.myradio:not(:checked)').on('change', function() { alert( this.value ); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="radio" name="myradio" id="1" class="myradio" value="1"> 1 <input type="radio" name="myradio" id="2" class="myradio" value="2"> 2 <input type="radio" name="myradio" id="3" class="myradio" value="3"> 3 

嘗試這個:

$(function() { 
    $("#r1, #r2, #r3").change(function () { 
        str = $(this).val();
        window.location = "http://www.example.com?variable=" + str;
    })
});`

<input type="radio" id="r1" value="1"> 1</input>
<input type="radio" id="r2" value="2"> 2</input>
<input type="radio" id="r3" value="3"> 3</input>

首先,您的無線電缺少名稱屬性,以了解單選按鈕組的名稱。 在你把這個名字寫成這樣的東西之后

jQuery("input:radio[name=GroupName]").click(function() {
    var value = jQuery(this).val();
    window.location.href = "http://www.example.com?variable="+value;
});

如果您想要跨瀏覽器兼容性(但使用更多DOM):

jQuery("input:radio[name=GroupName]").click(function() {
    var value = jQuery('input:radio[name=theme]:checked').val();
    window.location.href = "http://www.example.com?variable="+value;
});

更多信息請查看此問題: 在jQuery中,如何通過其name屬性選擇元素?

此外,在發布問題之前,您應該首先進行研究,因為大多數問題已經得到解答,您所需要的只是適應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM