jQuery Add and Remove Class

2019-03-06 05:10发布

I have this selector:

               <select name="type" id="type">
                    <option class="sub_1" value="1">1</option>
                    <option class="sub_2" value="2">2</option> 
                    <option class="sub_3" value="3">3</option> 
                    <option class="sub_3" value="4">4</option> 
                </select>

And then I have this one:

<select name="amount" id="amount">
   <option class="" id="valueAdd">   
</select>  

So, I wish to know how I can only add ONE class to that option. I have this code below, although, if I example select a different OPTION in my #type select, then it keeps the first class, and then just adds the second class too.

How can I do so it only adds one class? (Ie replace the other one)

jQuery:

   $(document).ready(function() {
        $("#type").change(function() {
            var typeid = ($(this).val()) 


        $("#valueAdd").addClass("sub_" + 
                  typeid);
        });
    });

标签: jquery class
2条回答
老娘就宠你
2楼-- · 2019-03-06 05:45
$("#valueAdd")[0].className = "sub_" + typeid;
查看更多
贼婆χ
3楼-- · 2019-03-06 05:51

Do removeClass first then addClass

   $("#valueAdd").removeClass().addClass("sub_" + typeid);

http://api.jquery.com/removeClass/

查看更多
登录 后发表回答