简体   繁体   English

Jquery:将更改事件附加到孩子

[英]Jquery: Attach change event to children

<form id="duration">
    <label for="change-chart-type-24H" >
        <input style="display:none;" name="chart-type" id="change-chart-type-24H" type="radio" value="24H">24H</label>
    <label for="change-chart-type-7D" >
        <input style="display:none;" name="chart-type" id="change-chart-type-7D" type="radio" value="7D" checked="true">7D</label>
    <label for="change-chart-type-30D" >
        <input style="display:none;" name="chart-type" id="change-chart-type-30D" type="radio" value="30D">30D</label>
</form>

I want to attach change() event to the radio buttons.我想将 change() 事件附加到单选按钮。

When I try like this当我像这样尝试时

$('input[type=radio][name="chart-type"]').change( function() {
});

It attaches the change() event only to the first radio button.它仅将 change() 事件附加到第一个单选按钮。

How can change the jQuery selector to attach the change() event to all the radio buttons?如何更改jQuery selector以将 change() 事件附加到所有单选按钮?

Note: When I console $('input[type=radio][name="chart-type"]') in the browser it shows only the first radio button.注意:当我在浏览器中控制台$('input[type=radio][name="chart-type"]')时,它只显示第一个单选按钮。

Try adding an ID or a class to all the radio buttons and select the buttons using that.尝试向所有单选按钮添加一个 ID 或一个类,然后使用它来选择按钮。 For instance:例如:

<label for="change-chart-type-24H" >
        <input class="radio-button" style="display:none;" name="chart-type" id="change-chart-type-24H" type="radio" value="24H">24H
</label>
<label for="change-chart-type-7D" >
        <input class="radio-button" style="display:none;" name="chart-type" id="change-chart-type-7D" type="radio" value="7D" checked="true">7D
</label>
    

and in your Jquery selection, you can use something like this:在您的 Jquery 选择中,您可以使用以下内容:

$(".radio-button").change( function() {
});

Also, make sure that all your jQuery is inside a $(document).ready(funciton(){})另外,请确保您所有的 jQuery 都在$(document).ready(funciton(){})

I tried it on my own and it seems to work.我自己尝试过,它似乎有效。 Here is what I have: https://codepen.io/habdeltawabae/pen/poyKQEP这是我所拥有的: https : //codepen.io/habdeltawabae/pen/poyKQEP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM