jquery - 如何使用 jQuery 切换相邻单元格内容

标签 jquery jquery-selectors

我正在从 MySQL 生成一张如下所示的表。当用户选中该复选框时,我想为该单元格着色,并理想将“非事件”一词切换为“事件”(反之亦然,当它未选中时)。

<table border="1" width="75%" class="stripeMe">
<thead>
    <tr>
        <th>Accounts</th><th>Status</th><th>Change</th>
    </tr>
</thead>
<tr>
    <td>M. Lamb</td><td class="c2"><span>Inactive</span></td><td><input type="checkbox" name="checks[]" id="R2C3" /></td>
</tr>
<tr>
    <td>B. Peep</td><td class="c2"><span>Active</span></td><td><input type="checkbox" name="checks[]" id="R3C3" /></td>
</tr>
<tr>
    <td>J. Spratt</td><td class="c2"><span>Active</span></td><td><input type="checkbox" name="checks[]" id="R4C3" /></td>
</tr>
<tr>
    <td>H. Dumpty</td><td class="c2"><span>Inactive</span></td><td><input type="checkbox" name="checks[]" id="R5C3" /></td>
</tr>

根据我从此处搜索中学到的知识,我可以切换包含复选框的单元格并使用以下命令更改相邻单元格单词:

$(document).ready(function() {
    $("input[type=checkbox]").click(function(e) {
        var bgColor = $(this).attr('checked') == 'checked' ? '#f00' : '#fff';
        var txtStatus = $(this).attr('checked') == 'checked' ? 'changed' : 'unchanged';
        //toggle the checkbox cell when clicked
        $(this).closest('td').css('background', bgColor);
        //toggle the inactive
        $(this).closest('td').siblings().find('span').text(txtStatus);
    });
});

我感觉我已经很接近了,但似乎找不到我的路! Here是我的测试 fiddle 。

最佳答案

另一个选项:http://jsbin.com/ahitiv/8/edit#javascript,html

$(document).ready(function(){
    $("tr").each(function(idx){
        $(this).click(function(){
           var rowid = idx;
           rowid = "#" + rowid;
           var rowtext = $(rowid).text();
           if (rowtext == "Inactive")
              $(rowid).text("Active");
           else
             $(rowid).text("Inactive");

        });

     });

});

关于jquery - 如何使用 jQuery 切换相邻单元格内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8683514/

相关文章:

javascript - 在 Chrome 扩展中,更改发送到特定域的 ajax 请求的引荐来源网址?

jquery - 在 Cytoscape.js 中查找 x,y 位置的元素

jquery - jQuery 中不同语法有什么区别?

javascript - 将 Puppeteer 页面作为函数中的参数传递未按预期工作

jQuery - 在 ID 属性中发布引用带有小数点的单选按钮

javascript - getElementById 和 JQuery 不返回相同的结果

对象的Javascript变量赋值返回字符串

jquery - jquery代码中 undefined variable

javascript - $(window).width() 与 $(document).width() 之间的区别

javascript - 显示/隐藏从函数中提取的标记