jQuery:对单选按钮选择执行特定操作

时间:2014-05-09 09:46:10

标签: jquery html twitter-bootstrap radio-button

我有几个来自 bootstrap 的单选按钮,如下所示。

<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
 <input type="radio" name="options" id="option1"> Option 1
</label>
<label class="btn btn-primary">
 <input type="radio" name="options" id="option2"> Option 2
</label>
<label class="btn btn-primary">
 <input type="radio" name="options" id="option3"> Option 3
</label>
</div>

如何为jQuery中的每个单选按钮执行特定操作?

例如:

如果选中option1 - &gt;加载“html1.html”
如果选中option2 - &gt;加载“html2.html”

我使用此代码在特定div中加载html代码:

<script>
   $(document).ready(function(){ 
       $('#main-content').load('skill-temp.html');
   });
</script>

4 个答案:

答案 0 :(得分:1)

您可以这样做:

$('input[name="options"]').change(function() {
    var num = this.id.match(/\d+$/);
    $('#main-content').load('html'+num+'.html');
});

答案 1 :(得分:0)

我认为最简单的方法是在输入中使用数据属性,指导jQuery加载操作。类似的东西:

 <input class="loadhtml" data-html="page1" type="radio" name="options" id="option1">
 <input class="loadhtml" data-html="page2" type="radio" name="options" id="option2">
 <input class="loadhtml" data-html="page3" type="radio" name="options" id="option2">

然后

 <script>
 $('input.loadhtml').on('change', function(){
    var data = $(this).data('html');
    $('#main-content').load(data + '.html');
 });
 </script>

修改

A fiddle,唯一的区别是我传递警报(数据)而不是调用load

答案 2 :(得分:0)

我找到了Answer

$(document).on('change', 'input:radio[class^="loadhtml"]', function (event) {
 var data = $(this).data('html');
$('#main-content').load(data + '.html');
});

将class =“loadhtml”添加到每个单选按钮

<div id="nav" class="btn-group btn-group-vertical" data-toggle="buttons">
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" data-html="Skills" name="options"><span class="fa fa-lock"></span> About
</label>
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" name="options"><span class="fa fa-unlock"></span> Skills
</label>
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" name="options"><span class="fa fa-unlock"></span> Education
</label>
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" name="options"><span class="fa fa-unlock"></span> Timeline
</label>
<label class="btn btn-primary">
    <input class="loadhtml" type="radio" name="options"><span class="fa fa-unlock"></span> Hobbies</label>

答案 3 :(得分:-1)

$('input:radio[name="options"]').change(
        function(){

            var id =this.id;
            if ( id  == 'option1') {
               // call html page 1
            }
             else if( id  == 'option2'){
              // call html page 2

             }    

        });