【问题标题】:get child element that gets selected inside div element [duplicate]获取在 div 元素中被选中的子元素 [重复]
【发布时间】:2015-05-12 15:42:13
【问题描述】:

如何获取从我的 div 中选中的单选按钮

这是我的 jquery,但 c 返回未定义

$('#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>

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

使用 :checked 选择器

$('#SpaceType').change(function () {
  var c  = $(this).find(':checked').attr('id');
  alert(c)
});
<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>

在您的情况下,您正在迭代 SpaceType 的子元素,它们是 label 元素并且它们没有 id,而且您正在阅读称为 iddata 而不是 @987654328 @ 属性。

【讨论】:

  • 不值得写一个新的答案,但是在原生 JavaScript 中检索 id 也是微不足道的:c = this.querySelector('input:checked').id;
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 2011-04-04
  • 1970-01-01
相关资源
最近更新 更多