我想出了一個解決方案。如果這是一個錯誤的方法,請糾正我。
我加入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