选中复选框后,我将显示一个表格。如果表格被取消,我希望取消选中该框。

编辑

在表格形式(第二个形式)上,滚动到复选框并选中一个,然后转到第一个形式并单击“取消”按钮。向下滚动到您选中的框。

jsfiddle

在HTML中,我定义:

<input id="current-checkbox" type="checkbox" class="hidden" />


在关联的JS中,我保存当前位置:

var curRow = $(this).closest('.trow').find('input[type=checkbox]');
$("#current-row",curRow);


console.log显示:

$("#current-checkbox")
[<input id=​"current-checkbox" type=​"checkbox" class=​"hidden">​]


取消表单JS:

$("#cancel-email").on('click', function (e) {
    debugger
    e.preventDefault();
    setTimeout(function () { showMessage(1, 'Emails not sent.') }, 2000);
    setTimeout(function () { hideEmailElems(); }, 2000);
    $("#current-checkbox").find("input[type=checkbox]").prop("checked", false).focus();
});


console.log:

$("#current-checkbox").find("input[type=checkbox]").length
0


复选框已找到的正确jQuery选择器是什么?

最佳答案

$("#current-checkbox")仅选择一个元素(即复选框),因为它是ID的选择器。

find(selector)方法在匹配的元素中查找与选择器匹配的子元素,因此在这种情况下,$("#current-checkbox").find("input[type=checkbox]")为空,因为该复选框元素没有任何子元素。

因此,您不需要该.find()部分。 $("#current-checkbox")就足够了。

请注意,在有效的HTML中,the id attribute必须是唯一的。因此,id选择器最多匹配一个元素。


  如何在表格行中保存对复选框的引用?


您无需保存对选中复选框的引用。您可以改为使用:checked选择器从任何地方找到它。

$("#cancel-email").on('click', function(e) {
    // Un-check the checked checkbox
    $(".trow input[type=checkbox]:checked").prop("checked", false);

    // Hide the E-Mail box
    $('#main-container').hide();
});

07-24 09:44
查看更多