簡體   English   中英

如何通過單擊並使用JavaScript將最后一個更改單元更改為原始單元來更改HTML表格單元-(總機)

[英]How to change HTML table cell by clicking and changing last change cell to original using JavaScript – (Switchboard)

我有一個HTML表,每個單元格都有一個值“關”。 當用戶單擊一個單元格時,我只想將該單元格的值更改為“開”,如果用戶單擊另一個單元格,則將其更改為“開”,則將先前更改的單元格重新設置為“關”。 就是 只有一個單元格顯示為“ On”,其他所有單元格均顯示為“ Off”。 必須僅使用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>

這是我嘗試過的:

<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>

我可以更改為“開”,但是我不知道如何將其他單元格設置為“關”。 有人可以幫忙嗎?

您可以使用簡單的點擊處理程序來執行此操作

 $('#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> 

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

基本上,添加$(".switch").text("Off"); 會將其所有文本設置為“關”,然后再將其更改為“開”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM