当条件为字符串的一部分时,尝试根据条件在标签内添加/更改类

时间:2018-11-10 04:23:24

标签: javascript css coffeescript

当标记是coffeeScript中字符串的一部分时,如何根据条件更改类:

changeOptions(): void {
    const newOptions: ClassOption = new ClassOption("something");
    Object.assign(this.options, newOptions);
    // Note that after this, `this.options`' reference is preserved.
} 

如果aScore> hScore,如何将class ='name'更改为class ='winning'?

我已经尝试过......

class ClassA {
   constructor() {
      // 1. Initialise with an empty object:
      this.options = {};
      
      // 2. Pass that reference to ClassB instead of undefined:
      this.B = new ClassB(this.options);
      
      this.changeOptions();
   }
   
   changeOptions() {
      // 3. Mutate this.options without changing its reference:
      Object.assign(this.options, {
        opt1: 1,  
        opt2: 2, 
      });
      
      // 3. You can also do it like this:
      this.options.opt3 = 3;
   } 
}

class ClassB {
   constructor(options) {
      this.options = options;
   }
   
   getOptions() {
      return this.options;
   }
}
 
const a = new ClassA();

a.changeOptions();

console.log(a.B.getOptions());

但出现意外的标识符错误。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

期望aScore和hScore为整数。 然后这应该起作用,

var res_class = ( aScore > hScore ) ? 'winning' : 'name';

rows+= "<tr class='row'>" + 
         "<td class='"+res_class+"'>" + awayTeam + "</td>" +
         "<td class='score'>" + aScore + "</td>" +
         "<td class='name'>" + homeTeam + "</td>" +
         "<td class='score'>" + hScore + "</td>"  +
         "<td class='period'>" + currentPeriod + "</td>" +
       "</tr>";
table = "<table class='data'>" + rows + "</table>";

return table

答案 1 :(得分:0)

您可以使用以下命令: 您必须分别选择ascorehscore来比较值,所以我将其类名更改为score-ascorescore-hscore

条件发生后,将name类更改为winning

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
</body>

<script type="text/javascript">
  $(document).ready(function(){
      $('body').html(create())
      var ascore = $('.score-ascore').text()
      var hscore = $('.score-hscore').text()
      if(aScore>hScore){
        var element = $("td.name")
        element.addClass("winning")
        element.removeClass("name")
      }

  })

  function create(){
    awayTeam = 10
    aScore = 10
    homeTeam = 10
    hScore = 9
    currentPeriod = 10
    rows = 10
    rows+= '<tr class="row">' + 
         '<td class="name">' + awayTeam + '</td>' +
         '<td class="score-ascore">' + aScore + '</td>' +
         '<td class="name">' + homeTeam + '</td>' +
         '<td class="score-hscore">' + hScore + '</td>'  +
         '<td class="period">' + currentPeriod + '</td>' +
       '</tr>'
      table = '<table class="data">' + rows + '</table>'
      return table
  }
</script>
</html>