2016-12-12 15 views
0

我目前在更改JavaScript函數中的全局變量值時遇到了問題。我使用的代碼如下:在JavaScript中更改全局變量的問題

<script> 
 
    var open = false; 
 
    $('.header').click(function() {  
 
     $(this).find('span').text(function (_, value) { 
 
      alert(open); 
 
      if (open == false) { 
 
       $(this).addClass('fa fa-minus-circle'); 
 
       open == true; 
 
      } else { 
 
       $(this).addClass('fa fa-plus-circle'); 
 
       open == false; 
 
      } 
 
      /*return value == '+' ? '-' : '+' */ 
 
     }); 
 
     $(this).nextUntil('tr.header').slideToggle(100, function() { 
 
     }); 
 
    }); 
 
</script>

我想改變類span元素的每次我一下就可以了(開/關),但它只是改變了類第一時間和全局變量值總是保持錯誤。

我試圖在文檔準備好之前在函數外部聲明全局變量,但仍然存在相同的問題。 我在做什麼錯?

+1

順便說一句,你的代碼覆蓋'window.open'方法。更好地使用局部變量。 – Bergi

+1

而.addClass不會替換,而是附加。你應該使用這樣的:$(this).removeClass('fa-minus-circle fa-plus-circle')。addClass(...) – Wizard

回答

4

當您使用=====進行比較時,例如open == true。將其更改爲open = trueopen = false

我已納入@Bergi's@Wizard's評論。另外把類fa放在相關的html元素上。您不必一直添加刪除它。

// a module to make the open variable local 
(function() { 

    var open = false; 
    $('.header').click(function() { 
    $(this).find('span').text(function(_, value) { 
     alert(open); 
     if (open == false) { 
     // remove plus before adding minus 
     $(this).removeClass('fa-plus-circle') 
      .addClass('fa-minus-circle'); 
     open = true; // change to assignment 
     } else { 
     // remove minus before adding plus 
     $(this).removeClass('fa-minus-circle') 
      .addClass('fa-plus-circle'); 
     open = false; // change to assignment 
     } /*return value == '+' ? '-' : '+' */ 
    }); 
    $(this).nextUntil('tr.header').slideToggle(100, function() {}); 
    }); 

})(); 
+0

謝謝你,先生,這解決了這個問題! –

0

請試試這個...
還要注意的是,「==operator主要是用來分配新值的變量。

<div class="header"> 
    <span></span> 
</div> 

<script> 
    var open = false; 
    $('.header').click(function() { 
     $(this).find('span').text(function (_, value) { 
      console.log(open);//better way to examine code 

      if (!open) { 
       $(this).addClass('fa fa-minus-circle'); 
       //open == true; This can only be used as a condition... 
       open=true;//but here you re-assign a new property/value and then the variable changes 

      } else { 
       $(this).addClass('fa fa-plus-circle'); 
       //open == true; This can only be used as a condition... 
       open=true;//but here you re-assign a new property/value and then the variable changes 

      } 

      //Perhaps you might also be interested in using tenary operators... 
      !(open)?(function(e){ 
       open=true; 
       $(e).addClass('fa fa-minus-circle'); 
      })($(this)):(function(){ 
       open=true; 
       $(e).addClass('fa fa-minus-circle'); 
      })($(this)); 

     }); 
     $(this).nextUntil('tr.header').slideToggle(100, function() { 

     }); 
    }); 
</script>