Automatically close all the other
tags after opening a specific
tag

前端 未结 6 509
日久生厌
日久生厌 2021-02-06 01:08

Here is my code.



        
6条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 01:20

    I have come up with a solution. Please correct me if this is a wrong approach.

    I added an onclick event to all of the details tag and made a function thisindex(this) which returns the index of the clicked tag and the obtained index number is then passed to the another function closeAll() which minimizes/closes all the other open tags except for one whose index matches with what we obtained earlier.

    Here is the code.

    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
    1Demo 1
    2Demo 2
    2Demo 3

    Same with the help of jQuery

    $(document).ready(function(){
      $('details').click(function (event) {
        var index = $('details').index(this);
        var len = $("details").length;
        for(var i=0; i

    Kindly suggest me a better approach if this not up to the mark.

提交回复
热议问题