如果至少 1 个所选项目具有自定义属性,如何隐藏 HTML5 分隔符?

How to hide HTML5 dividers when if at least 1 selected item has a custom attribute?

我有一个包含多个 HTML 复选框的表单。仅当 至少一个 选中的复选框具有名为 "terminator" 的自定义 HTML5 属性时,我才想隐藏一些分隔线。否则我想显示分隔线。

我试图通过使用 change() 事件来检查是否具有 terminator 属性来完成此操作。

这是我所做的。

$("input[type='checkbox']").change(function(e) {

    var className = 'terminated_' + getContronId($(this).attr('name'));

    var existingElements = $('#survey-optional-controls').val().split('|') || [];


    //Hide all groups that have the class equal to className
    if( $(this).is(':checked') ){

        if( $(this).data('terminator') ){
            hideControls($(this), existingElements, className);
        }

    } else {

        showControls(existingElements, className);

    }

}).change();

函数hideControls将隐藏需要的输入。函数 showControls 将显示所需的输入(如果有的话)。

我的代码可以正常工作,但有一个问题我无法找到解决方案。选中具有 terminator 属性的框并选中不具有 terminator 属性的框,然后 "un-checking" 不具有 [=13= 属性的框后,会出现此问题] 属性。

当第一次选中带有 terminator 属性的框时,分隔符会按预期隐藏。

然后,当取消选中一个没有 terminator 属性的框时,它会显示应该隐藏的分隔线,因为我仍然有 1 个带有 terminator 属性的复选框。

我该如何解决这个问题?

我创建这个 jFiddle 是为了展示代码和实际问题。您可以通过跳转到 jFiddle 上的“1:b) 更多问题”部分来重新创建问题,然后选中 "Red" 框,然后选中 "Green - Terminator" 框,最后取消选中 "Red" 框。由于 "Green - terminator" 仍处于选中状态,您将看到下面的分隔线将如何出现在它们应该隐藏的位置

下面的代码表示'If any input that have the type checkbox is changing'

$("input[type='checkbox']").change(function(e) { /*hide*/ }
else { /*show*/}

当您取消选中 "red" 复选框 this="red" 并且未选中红色时...它会自动转到显示分隔符的 else 语句

为了确保 showControls 仅在具有 data-terminator 属性的复选框未选中时才会被调用,

改变这个:

...

} else {
    showControls(existingElements, className);
}

...

} else if ($(this).is("[data-terminator]")) {
    showControls(existingElements, className);
}

已更新 jsFiddle:http://jsfiddle.net/8yf0v3xt/10/

您应该检查复选框的 "checked" 状态,并在每次更改时设置数据终止符属性。

类似

$("input[type='checkbox']").change(function(e) {
  var className = 'terminated_' + getContronId($(this).attr('name'));
  var existingElements = $('#survey-optional-controls').val().split('|') || [];

  var isTerminatorChecked = $("input:checkbox[data-terminator='Yes']").is(":checked");

  //Hide all groups that have the class equal to className
  if (isTerminatorChecked) {
    hideControls($(this), existingElements, className);
  } else {
    showControls(existingElements, className);
  }
});

Updated fiddle