开发者

Self referencing list items in html for ordered lists

开发者 https://www.devze.com 2023-03-16 05:39 出处:网络
Is there a way to have a self referencing \'list item\' in html so when I reference a number or letter in an ordered list it keeps track of changes.Therefore, when I add or remove list items it automa

Is there a way to have a self referencing 'list item' in html so when I reference a number or letter in an ordered list it keeps track of changes. Therefore, when I add or remove list items it automatically change the references to update to the new ordered list number or letter.

If this type of self 开发者_开发知识库referencing is not possible in older html versions how about in html5?

Also is this type of referencing available in javascript or a javascript framework like jQuery?


Given HTML like

<ol title="Figure 1">
  <li id="poundcake">Pound Cake</li>
  <li id="spongecake">Sponge Cake</li>
</ol>

<p>The most delicious from the list above is <label for="spongecake">.</p>

and then at the bottom (or onload),

<script>(function () {

  // From http://stackoverflow.com/questions/5395177/ordered-list-index
  function itemIndex(listItem) {
    var index = 0;
    for (var sibling = listItem; sibling;
         sibling = sibling.previousSibling) {
      if (sibling.tagName == "LI") {
        var value = +sibling.value;
        if (value) {
          return value + index;
        }
        ++index;
      }
    }
    var start = +listItem.parentNode.start || 1;
    return start + index - 1;
  }

  var labels = document.getElementsByTagName("label");
  for (var i = 0, n = labels.length; i < n; ++i) {
    var label = labels[i];
    var id = label.getAttribute("for");
    if (!id) { continue; }
    var target = document.getElementById(id);
    if (!target || target.tagName !== "LI") { continue; }
    var replacementText = (target.parentNode.title || "")
        + " item " + itemIndex(target);
    label.parentNode.replaceChild(
        document.createTextNode(replacementText), label);
  }

}())</script>


Maybe this will help: Ordered List Index

0

精彩评论

暂无评论...
验证码 换一张
取 消