简体   繁体   English

jQuery根据选择的值更改选择文本

[英]jQuery change text of select depending on selected value

I'm trying to change the text color of the selection box depending on the selected value. 我正在尝试根据所选值更改选择框的文本颜色。

it's working, kind of. 它正在工作,有点。 Is there a way to not apply the css to the entire element and only to the selection box itself? 有没有办法不将CSS应用于整个元素,而仅应用于选择框本身?

https://imgur.com/JJ3jSso when I apply the gray color all of the elements get gray. https://imgur.com/JJ3jSso当我应用灰色时,所有元素都会变成灰色。 Is it possible that only the "( keine )" is gray when the selection box is collapsed? 选择框折叠时,是否只有“(keine)”是灰色的?

$('select').on('change load', function(){
// console.log($(this).children("option:selected").val());
  if($(this).children("option:selected").val() == "keine"){
    $(this).css('color', '#BFBFBD');
  } else {
    $(this).css('color', '#000');
  }
});

$('select').trigger('change');

HMTL Code: HMTL代码:

<select>
  <option value="keine">( keine )</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

https://jsfiddle.net/1keyup/bfd74h5k/1/ https://jsfiddle.net/1keyup/bfd74h5k/1/

You can get the selected value and check if it equals 'keine'. 您可以获取选定的值,并检查它是否等于“ keine”。 Then apply gray color: 然后应用灰色:

$('select').on('change', function(){
  const value = $(this).val();
  if(value === 'keine') {
    // apply glay color
  } else {
    // apply default color
  }
});

Demo (It's just a quick sample, can be refactored of course:)) 演示 (这只是一个快速示例,当然可以重构:)

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

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