单选按钮-如何检查链接并将用户发送到URL [英] radio button - how to check a link and send user to URL

查看:66
本文介绍了单选按钮-如何检查链接并将用户发送到URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据单选按钮选择找到检查URL的最佳方法.在我的页面上,我至少有5对单选按钮.有人可以告诉我,根据用户选择的单选按钮向用户发送正确网址的最佳方法是什么?

I'm trying to find the best way of checking a url based on a radio button selection. On my page, I have at least 5 pairs of radio buttons. Can someone tell me what's the best way of sending the user to the correct url based on their selected radio button?

$(document).ready(function () {
    $("*[type=radio]").change(function () {
       alert( $(this).attr("value"))
    })
});

查看更多代码: jsfiddle

推荐答案

根据您的jsfiddle,您的单选按钮对是按顺序命名的:第一对命名为1,第二对命名为2,等等.您可以使用它为循环中的按钮分配一个侦听器.首先,为每个按钮提供一个与单选按钮组名称匹配的ID,并为它们提供一个将其标识为组的类,如下所示:

Based on your jsfiddle, your radio button pairs are named in sequential order: the first pair is named 1, the second pair is named 2, and so on. You can use this to assign a listener to the buttons in a loop. First, give each button an id that matches the radio button group name, and a class to identify them as a group, as follows:

<div>
    <ul>
        <li>
            <input type="radio" name="1" value="http://www.google.com" checked="checked" id="radio-1">
            <label for="radio-1"><strong>link 1</strong></label>
        </li>
        <li>
            <input type="radio" name="1" value="http://www.bing.com" id="radio-2">
            <label for="radio-2"><strong>link 2</strong></label>
        </li>
    </ul>
</div>
<p>
    <button id='button_1' href="#" class="radio-redirect btn btn-primary">GO !</button>
</p>

因此,您最终将获得一堆这样的按钮.然后,您需要遍历它们并为他们提供一个侦听器:

So you'll end up with a bunch of those buttons. Then you need to loop through them and give them a listener:

$.each($('.radio-redirect'), function(i, item) {
    var id = $(item).prop('id');
    var idparts = id.split('_'); // idparts[1] is now the number portion of the id
    $(item).click(function() {
        location.href=$('input[name='+idparts[1]+']:checked').val();
    });
});

这是一个jsfiddle ,其中我已将location.href分配替换为alert调用,所以包含执行代码的框架不会消失.只要您与命名标准一致,就可以使用.如果将单选按钮名称更改为radiobutton_1而不是简单的1,则只需修改location.href行以包含全名即可.

Here's a jsfiddle where I've replaced the location.href assignment with an alert call, so that the frame that contains the executing code won't go away. As long as you are consistent with your naming standard, this will work. If you change your radio button names to, say radiobutton_1 instead of simply 1, you just modify the location.href line to incorporate the full name.

如果您 与您的命名不一致,则必须手动将click事件分配给每个按钮,而不是能够循环执行.但这仍然可以做到.

If you are not consistent with your naming, then you'll have to manually assign the click events to each button, rather than being able to do it in a loop. But it can still be done.

这篇关于单选按钮-如何检查链接并将用户发送到URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆