Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - How to dynamically add class when I select option

I want to dynamically add class for this selected class.

HTML :

<select name="number" id="paragraphSpaceOPtion">
    <option class="option-1" value="00">00</option>
    <option class="option-2" value="05">05</option>
    <option class="option-3" value="07">07</option>
    <option class="option-4" value="10">10</option>
    <option class="option-5" value="15">15</option>
    <option class="option-6" value="20">20</option>
</select>

Here is a content I wan't to add class:

<div class="content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, in!</p>
</div>

JS :

$(document).ready(function(){

    var e = document.getElementById("paragraphSpaceOPtion");
    var strUser = e.options[e.selectedIndex].value;
    //console.log("option number " + strUser);

    //var masud = typeof(strUser);
    //console.log(masud);
    if(strUser == "00"){
        $(".content").addClass("option-no-00");
    }
    if(strUser == "05"){
        $(".content").addClass("option-no-05");
    }
    if(strUser == "07"){
        $(".content").addClass("option-no-07");
    }
    if(strUser == "10"){
        $(".content").addClass("option-no-10");
    }
    if(strUser == "15"){
        $(".content").addClass("option-no-15");
    }
    if(strUser == "20"){
        $(".content").addClass("option-no-20");
    }
})

I wan't to dynamically add class name when I select option.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here you go with one more solution

var prevVal;
$("#paragraphSpaceOPtion").on("change",function(){
  var val = $(this).find('option:selected').val();
  $(".content").removeClass(`content-${prevVal}`).addClass(`content-${val}`);
  prevVal = val;
});
.content-00{ color:pink}
.content-05{ color:blue}
.content-07{ color:green}
.content-10{ color:red}
.content-15{ color:yellow}
.content-20{ color:gray}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="number" id="paragraphSpaceOPtion">
  <option class="option-1" value="00">00</option>
  <option class="option-2" value="05">05</option>
  <option class="option-3" value="07">07</option>
  <option class="option-4" value="10">10</option>
  <option class="option-5" value="15">15</option>
  <option class="option-6" value="20">20</option>
</select>


<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus, in!</p>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...