获取在div元素中选择的子元素

时间:2015-03-11 00:43:12

标签: javascript jquery html

如何获取从div内部检查的单选按钮

这是我的jquery,但是c返回undefined



$('#SpaceType').change(function () {
    var kids = $(this).children();
    $(kids).each(function() {
        var c = $(this).data('id');
    });
});




这是我的div



<div class="btn-group" data-toggle="buttons" id="SpaceType">
                    <label id="SpaceTypeLabelHouse" class="btn btn-primary">
                        <input type="radio" name="typeoptions" autocomplete="off" id="0"> House
                    </label>
                    <label id="SpaceTypeLabelApartment" class="btn btn-primary">
                        <input type="radio" name="typeoptions" autocomplete="off" id="1"> Apartment
                    </label>
                    <label id="SpaceTypeLabelStudio" class="btn btn-primary">
                        <input type="radio" name="typeoptions" autocomplete="off" id="2"> Studio
                    </label>
                    <label id="SpaceTypeLabelOther" class="btn btn-primary">
                        <input type="radio" name="typeoptions" autocomplete="off" id="3"> Other
                    </label>
                </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

使用:选中的选择器

&#13;
&#13;
$('#SpaceType').change(function () {
  var c  = $(this).find(':checked').attr('id');
  alert(c)
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="btn-group" data-toggle="buttons" id="SpaceType">
  <label id="SpaceTypeLabelHouse" class="btn btn-primary">
    <input type="radio" name="typeoptions" autocomplete="off" id="0"> House
  </label>
  <label id="SpaceTypeLabelApartment" class="btn btn-primary">
    <input type="radio" name="typeoptions" autocomplete="off" id="1"> Apartment
  </label>
  <label id="SpaceTypeLabelStudio" class="btn btn-primary">
    <input type="radio" name="typeoptions" autocomplete="off" id="2"> Studio
  </label>
  <label id="SpaceTypeLabelOther" class="btn btn-primary">
    <input type="radio" name="typeoptions" autocomplete="off" id="3"> Other
  </label>
</div>
&#13;
&#13;
&#13;

在您的情况下,您正在迭代SpaceType labelid元素的子项,而他们没有data,您也正在阅读{{1}调用id而不是id属性。