简体   繁体   English

如何获取输入值以添加为 jquery 中当前选定元素的类

[英]How get input value to add as class for current selected element in jquery

Hey guys i'm trying to make jquery code to change the icon's class by selecting radio input that has the value of class but the problem is its add the class vale to all others icons class's嘿伙计们,我正在尝试通过选择具有类值的无线电输入来制作 jquery 代码来更改图标的类,但问题是它将类 vale 添加到所有其他图标类的

here my code: HTML这是我的代码:HTML

<div class="select-container">
    <input type="radio" value="icon-home">
    <input type="radio" value="icon-car">
    <input type="radio" value="icon-sky">
    <input type="radio" value="icon-color">
</div>


<div class="container-icons">
    <a>
        Home Icon: <i class="icon"></i> <button class="select"></button>
    </a>
    <a>
        Car Icon: <i class="icon"></i>  <button class="select"></button>
    </a>
    <a>
        Sky Icon: <i class="icon"></i>  <button class="select"></button> 
    </a>
    <a>
        color Icon: <i class="icon"></i> <button class="select"></button>
    </a>
</div>

Jquery:查询:

<script>
    jQuery('body').on('click' , '.select' , function() {

        jQuery('.select-container').show();

        $('.select-container').on('change', function () {

            var icon_value = $("input[type='radio'][name='icon']:checked").val();

            $('.icon').addClass(icon_value);

        });

    });

</script>

On click, use .index to get the index of the selected radio among its siblings.单击时,使用.index获取所选电台在其兄弟姐妹中的索引。 Then with .eq , you can select the same index of the .icon s and add the appropriate class.然后使用.eq ,您可以选择.icon的相同索引并添加适当的类。

 $('.select-container input').on('change', function() { const value = $(this).val(); const index = $(this).index(); console.log(index); $('.icon').eq(index).addClass(value); });
 .icon-home { background: green; } .icon-car { background: yellow; } .icon-sky { background: blue; } .icon-color { background: orange; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="select-container"> <input type="radio" value="icon-home"> <input type="radio" value="icon-car"> <input type="radio" value="icon-sky"> <input type="radio" value="icon-color"> </div> <div class="container-icons"> <a> Home Icon: <i class="icon">A</i> <button class="select"></button> </a> <a> Home Car: <i class="icon">A</i> <button class="select"></button> </a> <a> Home Sky: <i class="icon">A</i> <button class="select"></button> </a> <a> Home color: <i class="icon">A</i> <button class="select"></button> </a> </div>

If you wanted to make only one radio button selected at a time, add the same name attribute to all the radio buttons.如果您想一次只选择一个单选按钮,请为所有单选按钮添加相同的name属性。

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

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