我想出了一个解决方案。如果这是一个错误的方法,请纠正我。
我加入onClick事件的所有细节标签的,并提出了功能thisindex(this)
它返回所点击的标签和所获得的索引号的索引随后被传递到另一个功能closeAll()
,其最小化/关闭所有其他打开的标签除了索引与我们之前获得的索引相匹配的索引。
这是代码。
function thisindex(elm){
var nodes = elm.parentNode.childNodes, node;
var i = 0, count = i;
while((node=nodes.item(i++)) && node!=elm)
if(node.nodeType==1) count++;
return count;
}
function closeAll(index){
var len = document.getElementsByTagName("details").length;
for(var i=0; i<len; i++){
if(i != index){
document.getElementsByTagName("details")[i].removeAttribute("open");
}
}
}
<details onclick="closeAll(thisindex(this));">
<summary>1</summary>Demo 1
</details>
<details onclick="closeAll(thisindex(this));">
<summary>2</summary>Demo 2
</details>
<details onclick="closeAll(thisindex(this));">
<summary>2</summary>Demo 3
</details>
用相同的jQuery
$(document).ready(function(){
$('details').click(function (event) {
var index = $('details').index(this);
var len = $("details").length;
for(var i=0; i<len; i++){
if(i != index){
$("details")[i].removeAttribute("open");
}
}
});
});
帮助请建议我一个更好的方法,如果这没有达到标准。
那你试试这么远吗? – Femaref