jQuery Add and Remove Class

2019-03-06 05:58发布

问题:

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);
        });
    });

回答1:

Do removeClass first then addClass

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

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



回答2:

$("#valueAdd")[0].className = "sub_" + typeid;


标签: jquery class