jquery/javascript隐藏除单击项之外的所有子表单元素
我使用的json模式库生成了很多html代码 我在这里创建了一个JSFIDLE: 更新的JSFIDLE: 基本上,每个表单组都由html5属性定义: div数据方案 从JSFIDLE中可以看到,所有form div元素都嵌套在以下位置:jquery/javascript隐藏除单击项之外的所有子表单元素,javascript,jquery,html,Javascript,Jquery,Html,我使用的json模式库生成了很多html代码 我在这里创建了一个JSFIDLE: 更新的JSFIDLE: 基本上,每个表单组都由html5属性定义: div数据方案 从JSFIDLE中可以看到,所有form div元素都嵌套在以下位置: <div data-schemaid="/properties/TLRoot"> </div> 而且,一旦我完成了这项工作,拥有一个通用函数将非常酷,而不是对每个菜单栏项重复此代码您的HTML非常长,内容相对较少。此外,某些菜单项具有折
<div data-schemaid="/properties/TLRoot">
</div>
而且,一旦我完成了这项工作,拥有一个通用函数将非常酷,而不是对每个菜单栏项重复此代码您的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();
});
请参阅如果链接未动态插入,则无需委托单击-您可以隐藏div.row>divFirst。这是无效的,而且您似乎有严重的道歉案例,生成的html远远超过我在JSFIDLE中粘贴的html。虽然减少了代码,但看起来我遗漏了很多结束div标记。
// 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();
});