2015-11-30 33 views
0

我有一個HTML表格,每個單元格的值都爲「Off」。當用戶點擊某個單元格時,我只想將該單元格的值更改爲「開啓」,如果用戶單擊另一個單元格將其更改爲「開啓」,則將先前更改的單元格恢復爲「關閉」。 IE瀏覽器。只有一個單元格顯示爲「開」,其他所有單元格都將顯示爲「關」。如何使用JavaScript單擊並將最後一個更改單元更改爲原始格式來更改HTML表格單元格(交換機)

<script type="text/javascript"> 
    $('#switchboard-container td').click(function() 
    { 
     setClickHandlers(); 
    }); 

    function setClickHandlers() { 
     // Click handlers that change the content of switches to 'On' or 'Off'. 
     var cells = document.querySelectorAll('# switchboard -container td'); 

     Array.prototype.forEach.call(cells, function (td) { 
      td.addEventListener('click', changeCell); 
     }); 
    } 

    function changeCell() { 
     if (this.textContent == "On") 
     { 
      this.textContent == "Off"; 
     } 
     else 
     { 
      this.textContent = "On"; 
     } 
    } 
</script> 

我可以改變爲「開」,但我不知道如何設置其他:這必須使用JavaScript和JQuery只(不angularJS)

<table id="switchboard-container"> 
    <tbody> 
     <tr> 
      <td class="switch">Off</td> 
      <td class="switch">Off</td> 
     </tr> 
     <tr> 
      <td class="switch">Off</td> 
      <td class="switch">Off</td> 
     </tr> 
    </tbody> 
</table> 

這是我嘗試做細胞「關閉。有人可以幫忙嗎?

回答

1

看看這個小提琴: https://jsfiddle.net/3fh4mLba/1/

基本上,增加$(".switch").text("Off");將文本設置爲「關閉「,然後再將其更改爲開啓。

+0

這工作。謝謝 – Dush

1

你可以有一個簡單的點擊處理程序來做到這一點

$('#switchboard-container td.switch').click(function() { 
 
    var $this = $(this); 
 
    if ($this.hasClass('on')) { //if the current element is on then we can just make it off 
 
    $this.text('Off'); 
 
    } else { 
 
    $this.text('On'); //make the current td on 
 
    $('#switchboard-container td.switch.on').removeClass('on').text('Off'); //make other td which are on as off 
 
    } 
 
    $this.toggleClass('on'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table id="switchboard-container"> 
 
    <tbody> 
 
    <tr> 
 
     <td class="switch">Off</td> 
 
     <td class="switch">Off</td> 
 
    </tr> 
 
    <tr> 
 
     <td class="switch">Off</td> 
 
     <td class="switch">Off</td> 
 
    </tr> 
 
    </tbody> 
 
</table>