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
927 views
in Technique[技术] by (71.8m points)

javascript - Change div background color based on text inside div

On this site I have a "status tag" (Diesel, Auto, Manual, etc) on each inventory picture. I want the background color of that tag to be changed based on the text that is within the DIV.

This is the code that I have so far:

<script>
$(function() {
    var text = $('.image-container>.status-tag').text().toLowerCase(), color;
    switch (text) {
     case 'Diesel':
        color = '#ff0000';
        break;
     case 'AUTO':
        color = '#6dc8bf';
        break;
     default:
        color = '#39d52d';
    }
    $('.image-container>.status-tag').css('background', color);
});
</script>

The default color is showing up, but for some reason, I cannot get the specified color to show based on the text inside the div.

This is not my own code, I found it on another thread(original code here), but can't seem to get it to work on my site. any help would be appreciated.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

$(function() {
    //var text = $('.image-container>.status-tag').text().toLowerCase(), color;
    $('.image-container>.status-tag').each(function(){
    	console.log($(this).text());
      var text = $(this).text().toLowerCase();
    	switch (text) {
     	case 'diesel':
        color = '#ff0000';
        break;
     	case 'auto':
        color = '#6dc8bf';
        break;
     	default:
        color = '#39d52d';
    	}
    	$(this).css('background', color);
    });
});
<!DOCTYPE html>
<body>
 <div class="image-container">
   <div class="status-tag" style="height:50px;width:50px;margin-top: 10px; margin-bottom: 10px;">Diesel</div>
   <div class="status-tag" style="height:50px;width:50px;margin-top: 10px; margin-bottom: 10px;">AUTO</div>
   <div class="status-tag" style="height:50px;width:50px;margin-top: 10px; margin-bottom: 10px;">Bleh</div>
  </div>
</body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

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

...