jQuery expand collapse all DT tags in definition l

2019-04-12 08:55发布

Here is an example of what I am trying to accomplish, except that it uses lists (UL and LI): http://homework.nwsnet.de/news/ea21_turn-nested-lists-into-a-collapsible-tree-with-jquery

My data is structured using DL, DT and DD tags, like this:

<dl>
  <dt>Root</dt>
  <dd>
    <dl>
      <dt>Coffee</dt>
      <dd>black hot drink</dd>
      <dt>Milk</dt>
      <dd>white cold drink</dd>
      <dt>Beer</dt>
      <dd>
        <dl>
          <dt>European</dt>
          <dd>Heineken</dd>
          <dt>Mexican</dt>
          <dd>Corona</dd>
        </dl>
      </dd>
    </dl>
  </dd>
</dl>

How can I use jQuery to turn each DT (and its corresponding DD content) into a collapsible/expandable node, ie a treeview?

2条回答
欢心
2楼-- · 2019-04-12 09:27

At it's most basic, you can simply use toggle with the click event handler to do this:

// When any dt element is clicked
$('dt').click(function(e){
    // All dt elements after this dt element until the next dt element
    // Will be hidden or shown depending on it's current visibility
    $(this).nextUntil('dt').toggle();
});

// Hide all dd elements to start with
$('dd').hide();

You will, of course, want to use toggleClass to add additional styles as appropriately, as well as other effects. See: http://www.jsfiddle.net/yijiang/EA4R5/1/

查看更多
干净又极端
3楼-- · 2019-04-12 09:43

The man himself John Resig has already a video explaning how to create such menu using DL, DT and DD tags. Check out:

查看更多
登录 后发表回答