foreach单选按钮显示更多信息

foreach radio button show more info

本文关键字:信息 显示 单选按钮 foreach      更新时间:2023-09-26

我试图为每个单选按钮制作,当点击它以显示带有更多关于点击标题的信息的div时,当点击另一个单选按钮时,显示关于该单选按钮的信息并隐藏另一个点击的按钮:

HTML:

<input type="radio" id="1" />
<div class="event1">
 content..
</div>
<input type="radio" id="2" />
<div class="event2">
 content..
</div>
<input type="radio" id="3" />
<div class="event3">
 content..
</div>

jQuery:

var i = 1;
while(i < 10) {
$('.event' + i).hide();
    $("#" + i).click(function() {
        $('.event' + i).show();
    });
i++;
}

HTML

<input type="radio" name="radio" id="1" />
<div class="event">
 content.. 1
</div>
<input type="radio" name="radio" id="2" />
<div class="event">
 content.. 2
</div>
<input type="radio" name="radio" id="3" />
<div class="event">
 content.. 3
</div>

JS-

$('input[name=radio]').click(function() {
    $('.event').hide();
    $(this).next('.event').show();
});

CSS

.event {
    display: none;
}

Fiddlehttp://jsfiddle.net/UKn6D/

您可以尝试使用"each"更改循环

$(function(){
 $("input[type='radio']").each(function(){
  $(this).change(function(){
   if ($(this).is(':checked'))
    $(this).next().show();
   else
    $(this).next().hide();
  });
 });
});

如果你给无线电元素分配一个类来专门关注它们,那将是更可取的。像"radioElements"这样的东西就足够了。或者,您也可以将id与启动器一起使用:"radio_1"、"radio_2",然后使用输入[id^='radio_']。

在所有情况下,您都可以使用"each"函数。

更深入地说,如果你想切断所有其他无线电"信息",请将其更改为:

$(function(){
 $("input[type='radio']").each(function(){
  $(this).change(function(){
   if ($(this).is(':checked')) {
    $("input[type='radio']").next().hide();
    $(this).next().show();
   }
  });
 });
});
$('input[type="radio"]').on('change', function() {
  var id = $(this).attr('id'); //Get the ID from the selected radio button
  $('div:visible').hide(); //Hide visible Divs
  $('div.event' + id).show(); //Show matched Div
});

您需要为div提供一个额外的类名,并在此处更新jQuery代码。您还需要确保为输入元素指定一个name属性,以便它们都是同一组的一部分——假设它们是。

与其有一段时间看起来像那样,为什么不简单地使用呢

<div id="input-container">
<input class="clickable" />
<div class="content"></div>
</div>

这将适用于多个,jQuery可以像这个一样

$('#input-container input.clickable').click(function() {
$(this).parent().find('div.content').hide();
$(this).next('div.content').show();
});

我还没有真正测试过以上内容,但我相信它应该对你有效;拥有容器ID的原因只是为了加快jQuery的速度,因为通过#elementID第一个连接会更快