javascript - 为 Bootstrap 单选按钮上的单击/更改添加事件监听器

标签 javascript jquery twitter-bootstrap

我正在制作一个商店过滤器,我需要动态获取已选择的单选按钮的值,并以该值作为参数执行过滤器函数。

我的 HTML 是

<div class="btn-group-vertical btn-group-toggle pl-2" data-toggle="buttons">
    <label class="btn btn-secondary active">
        <input type="radio" name="option_all" id="option_gender" autocomplete="off" value="All" checked=""> Unisex
    </label>
    <label class="btn btn-secondary">
        <input type="radio" name="option_man" id="option_gender" autocomplete="off" value="Male"> Man
    </label>
    <label class="btn btn-secondary">
        <input type="radio" name="option_woman" id="option_gender" autocomplete="off" value="Female"> Woman
    </label>
</div>

我的想法是这样的

$(document).ready(function(){
    $('#option_gender').click(function(){
        filtefFunction(this.value)
    });
});

或者一个 addEventListener('click' func()) 到每个单选按钮...但我不知道如何做到这一点。

我更喜欢使用 vanilla js 的解决方案,因为我正在尝试在其中提高我的水平:)谢谢

最佳答案

在这种情况下我更喜欢做的是将事件委托(delegate)给父容器:

const select = document.getElementById('gender-selection');

select.addEventListener('click', ({ target }) => { // handler fires on root container click
  if (target.getAttribute('name') === 'option_gender') { // check if user clicks right element
    alert('Filter by: ' + target.value);
  }
});
<div class="btn-group-vertical btn-group-toggle pl-2" id="gender-selection" data-toggle="buttons">
  <label for="option_gender-unisex">Unisex</label>
  <input type="radio" name="option_gender" id="option_gender-unisex" value="All" checked="">

  <label for="option_gender-man">Man</label>
  <input type="radio" name="option_gender" id="option_gender-man" value="Male">

  <label for="option_gender-woman">Woman</label>
  <input type="radio" name="option_gender" id="option_gender-woman" autocomplete="off" value="Female">
</div>

作为旁注,您不想对不同的元素使用相同的 id,另一方面,如果您希望单选组只允许选择一个值 - 请使用相同的 name 属性。此外,autocomplete 属性对于 radio 类型的输入来说是多余的。它不会做任何事情。

UPD:从处理程序中删除了不必要的循环。

关于javascript - 为 Bootstrap 单选按钮上的单击/更改添加事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49097300/

相关文章:

javascript - 键作为变量导航 jsonp 对象

javascript - PhpStorm 替换为 js 正则表达式

javascript - 在html中使用 "&times"字改成×

javascript - 将URL中括号内的字符串转换为查询参数: Javascript

jquery - 为什么会出现双击?

javascript - 从多个按钮打开单个模态框

css - span10 offset1 未居中

javascript - CSS UI框架和jQuery UI有什么区别

Jquery和Ajax动态加载IFrame

javascript - 有什么办法可以加速 mousemove 事件吗?