javascript - jquery/javascript 隐藏除单击的项目之外的所有子表单元素

标签 javascript jquery html

我有相当多的 html 代码是从我正在使用的 json 模式库生成的。

我在这里创建了一个 jsfiddle:

更新了jsfiddle:https://jsfiddle.net/DTcHh/39070/

基本上每个表单组都是由 html5 属性定义的:

div data-schemaid

从jsfiddle中可以看到,所有表单div元素都嵌套在:

<div data-schemaid="/properties/TLRoot">
</div>

现在,当有人单击菜单栏上的某个项目时,它应该隐藏除单击的项目之外的所有表单组项目。

我尝试了以下代码,但似乎不起作用。

   $(document).on("click","#card-range",function(e) {
      e.preventDefault();
      //history.pushState({}, "", this.href);
$('[data-schemaid="/properties/TLRoot/"]').not($('[data-schemaid="/properties/TLRoot/properties/CardRangeList"]')).hide();
    });

    $(document).on("click","#hosts",function(e) {
      e.preventDefault();
      $('div[data-schemaid="/properties/TLRoot/"]').not($('div[data-schemaid="/properties/TLRoot/properties/HostList"]')).hide();
    });

另外,一旦我完成了这个工作,拥有一个通用函数就会很酷,而不是为每个菜单栏项重复此代码

最佳答案

您的 HTML 相当长,内容相对较少。此外,某些菜单项具有折叠/展开行为,因此单击它们将产生两种效果(折叠/展开以及子表单的隐藏/显示)。

无论如何,以下是让它发挥作用的方法:

// map the menu item with the section that needs to be shown
var dataForId = {
    "card-range": 'div[data-schemaid="/properties/TLRoot/properties/CardRangeList"]',
    "hosts": 'div[data-schemaid="/properties/TLRoot/properties/HostList"]'
    // extend as needed ...
};
// Extract the keys from the above object, and turn that into a selector
var selector = $.map(dataForId, function (value, key) {
    return '#' + key;
}).join(',');

$(document).on("click",selector,function(e) {
    e.preventDefault();
    // Hide all relevant sections. Due to the unnecessary nesting and lack of 
    //    useful things to select by, this is quite delicate code -- 
    //    meaning a slight change in the HTML could break this selector:
    $('div[data-schemaid="/properties/TLRoot"]>.well>div>div>.row>[data-schemaid]').hide();
    // Show only the one we need to have
    $(dataForId[this.id]).show();
});

请参阅updated fiddle

关于javascript - jquery/javascript 隐藏除单击的项目之外的所有子表单元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47115840/

相关文章:

javascript - 在 JavaScript 中调试正则表达式

JavaScript 表格输入

方法 ="put"的 Jquery 表单现已损坏

php - 使用 php 创建一个 html mailto

html - 重新格式化 css - 折叠冗余路径?

javascript - i18next - 语言切换无法正常工作

javascript - React Redux - bool 值未定义

javascript - 单击 Mapbox 中的 map 标记后更改其他 HTML 元素?

javascript - 无法从 JavaScript 的 iframe 中使用的内部页面获取正确的高度

html - 网站中未显示 CSS 字体样式