为什么我的if / else语句不起作用?

时间:2016-07-22 20:56:57

标签: javascript jquery if-statement

我看不出为什么我的if / else语句无法正常工作?

的JavaScript

var month_games = "Games";
var month_hit = "Hit";
var month_stake = "Stake";
var month_profit = "Profit";
var games_month = 0;
var hit_month = 0 + "%";
var stake_month = 0;
var profit_month = 0;

$( document ).ready(function(){
    document.getElementById("Games_Month").innerHTML = month_games;
    document.getElementById("Hit_Month").innerHTML = month_hit;
    document.getElementById("Stake_Month").innerHTML = month_stake;
    document.getElementById("Profit_Month").innerHTML = month_profit;
});


$('#January').click(function(){ 
    if ($('#Games_Month').innerHTML = month_games)
      {$('#Games_Month').innerHTML = games_month;}
    else {$('#Games_Month').innerHTML = month_games;}
});

HTML

<table class="table">
  <thead>
    <tr id="January">
      <th>January</th>
      <th id="Games_Month"></th>
      <th id="Hit_Month"></th>
      <th id="Stake_Month"></th>
      <th id="Profit_Month"></th>
    </tr>
  </thead>

现在,当我点击#january时,我希望其他ID的inner.HTML更改为另一个变量,但再次点击时,要将其更改回来。

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:2)

你忘记了if中的第二个=,而html()还没有innerHTML,因为你有一个jQuery对象,而不是DOM元素。

$('#January').click(function() { 
    if( $('#Games_Month').html() == month_games ) {
        $('#Games_Month').html(games_month);
    }
    else {
        $('#Games_Month').html(month_games);
    }
});

答案 1 :(得分:-1)

jQuery没有innerHTML,而是html()

单个=是分配,两个==是非严格比较,三个===是严格比较。

根本不需要if / else,只需使用正确的方法,例如html()和回调

$( document ).ready(function(){
    var stake_month  = 0;
    var profit_month = 0;
    var month_games  = "Games";
    var month_hit    = "Hit";
    var month_stake  = "Stake";
    var month_profit = "Profit";
    var games_month  = 0;
    var hit_month    = 0 + "%";

    $("#Games_Month").html(month_games);
    $("#Hit_Month").html(month_hit);
    $("#Stake_Month").html(month_stake);
    $("#Profit_Month").html(month_profit);

    $('#January').click(function(){ 
         $('#Games_Month').html(function(_, html) {
              return html === month_games ? games_month : month_games;
         });
    });
});