1

我试图根据是否选中单选按钮来编写用于隐藏/显示描述的 jquery/JS 逻辑。如果在页面加载时选中单选按钮,我希望加载与该单选按钮关联的描述。但是必须选择/选中其中一个的默认值

我确实尝试使用 .change 编写代码并单击 ready() 中的方法。但是没有成功

我只有两个单选按钮,我不是 Javascript/jquery 人。任何输入表示赞赏。这是一个例子

<div id="ServiceSelection">     
 <input type="radio" name="Service" checked="Checked" value="B"> Option 1
  <br>
 <input type="radio" name="Service" value="P"> Option 2
  <br>
  <div id="DivB" style="display:none" class="desc">B  Description goes here </div>
 <div id="DivP" style="display:none" class="desc">P Description goes here </div>    
</div> 

编辑DIV:

<div id="ServiceSelection">     
<input type="radio" name="Service" checked="Checked" value="B"> Option 1
<br>
<div id="DivB" style="display:none" class="desc">B  Description goes here </div>
<input type="radio" name="Service" value="P"> Option 2
<br>
<div id="DivP" style="display:none" class="desc">P Description goes here </div>    
</div> 

提前谢谢

4

3 回答 3

2
if($('input[name=Service]').is(':checked')){ //is it checked?
    var v = $('input[name=Service]:checked').val(); //get the value
    $('div[id$='+v+']').show(); //target the end of selector, and match it to our value
}

$('input[name=Service]').on('click', function(){
   $(this).parent().find('div').hide(); //hide the divs...
   $('div[id$='+$(this).val()+']').show(); //show the div based on our value again..
});    

小提琴

于 2013-03-29T22:44:20.883 回答
1

尝试这个:

function ShowData(evt) {
    var val = $("input[name=Service]:checked").val();
    if (val == 'B') {
        $('#DivB').show();
        $('#DivP').hide();
    } else {
        $('#DivP').show();
        $('#DivB').hide();
    }
}

$('input[name=Service]:radio').change(ShowData);
ShowData();

在这里演示

于 2013-03-29T22:43:54.077 回答
1

我建议:

// hide the div elements with JavaScript, so they're visible to those
// users with JavaScript disabled:
$('#ServiceSelection div[id]').hide();

// select the radio input elements and bind to the change event
$('input:radio').change(function(){
    // find the element whose id is equal to 'Div' + the value of the radio,
    // show that div, hide the sibling div elements
    $('#Div' + this.value).show().siblings('div').hide();
// filter the radio elements to find the one that's checked, and trigger the change event
}).filter(function(){return this.checked; }).change();

JS 小提琴演示

参考:

于 2013-03-29T22:51:18.990 回答