jQuery - 在 td 内选择输入(在同一行)

rav*_*ger 2 jquery jquery-selectors

HTML结构:

<tr>
<td class="edit"><input type="checkbox" class="editbox" /></td>
<td class="content"><input type="text" class="contentbox" size="40" disabled="disabled"/></td>
<td class="delete"><input type="checkbox" class="deletebox" /></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

我想要的是?当用户点击 input.editbox 时:

  • input.contentbox 变得可编辑
  • input.deletebox 变为未选中状态(如果之前已选中)

当用户点击 input.deletebox 时:

  • input.contentbox 被禁用
  • input.editbox 变为未选中状态(如果之前已选中)

我为那个结构做了这个:

<input type="checkbox" class="editbox"/>
<input type="text" class="contentbox" size="40" disabled="disabled"/>
<input type="checkbox" class="deletebox"/>
Run Code Online (Sandbox Code Playgroud)

通过使用 .next() 和 .prev()

$(document).ready(function () {
    $("#form input.editbox[type=checkbox]").each(function () {
        $(this).change(function () {
            if ($(this).is(":checked")) {
                $(this).next().removeAttr("disabled");
                $(this).next().next().attr('checked', false);
            } else {
                $(this).next().attr("disabled", "disabled");
            }
        });
    });
    $("#form input.deletebox[type=checkbox]").each(function () {
        $(this).change(function () {
            if ($(this).is(":checked")) {
                $(this).prev().attr("disabled", "disabled");
                $(this).prev().prev().attr('checked', false);
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

但是现在无法将 jQuery 代码转换为新结构。非常感谢任何帮助和想法。

Kas*_*syx 5

尝试parent().find(selector)

$(document).ready(function () {
    $("#form input.editbox[type=checkbox]").each(function () {
        $(this).change(function () {
            if ($(this).is(":checked")) {
                $(this).parent().parent().find('.contentbox').removeAttr("disabled");
                $(this).parent().parent().find('.deletebox').attr('checked', false);
            } else {
                $(this).parent().parent().find('.contentbox').attr("disabled", "disabled");
            }
        });
    });
    $("#form input.deletebox[type=checkbox]").each(function () {
        $(this).change(function () {
            if ($(this).is(":checked")) {
                $(this).parent().parent().find('.contentbox').attr("disabled", "disabled");
                $(this).parent().parent().find('.editbox').attr('checked', false);
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

在我看来,它比下一个更好的解决方案。这个更独立于你的 html 结构的变化。您可以重新排列 td 中的复选框,并且代码仍然有效。