创建并附加一个元素,innerHTML?恐怖...[请不要使用jquery]

发布于 2024-12-18 02:33:17 字数 1709 浏览 2 评论 0原文

我有一个按字母顺序返回列表的脚本,如下所示

<div id="x">
    <ul>
        <li>Apple
        <li>Banana
        <li>Blackberry
        <li>Blueberry
        <li>Cherry
        <li>Cranberry
    </ul>
</div>

但是列表中有很多项目(几乎 100 个),我希望按如下方式重新排列它们

<div id="x">
    <span id="A">A</span>
    <ul>
        <li>Apple
    </ul>
    <span id="B">B</span>
    <ul>
        <li>Banana
        <li>Blackberry
        <li>Blueberry
    </ul>
    <span id="C">C</span>
    <ul>
        <li>Cherry
        <li>Cranberry
    </ul>     
<div>

顺便说一句,我并没有真正对水果进行排序,这这只是一个例子。
它必须采用这种形式,出于无关紧要的原因,我只需要帮助创建和附加 span 元素和单独的列表。 我尝试过使用内部/外部 HTML,但我发现它真的非常困难。我目前有这样的东西:

function getAllLists()  
{  
var page = document.getElementById("x")
var allLists = page.getElementsByTagName("li");   
var num = allLists.length;  
//Some form of a for counter loop here
for (var counter = 0; counter < num; counter++) {   
    var first=allLists[counter].outerHTML;
    var second=allLists[counter+1].outerHTML;
    var firstletter= (allLists[counter].substring(0, 1)).toUpperCase();
    var secondletter= (allLists[counter+1].substring(0, 1)).toUpperCase();
    allLists[counter].outerHTML = '<span id="'+firstletter+'">'+firstletter+'</span>'+first;
    }
}

请避免使用 JQUERY。
我怎么强调都不为过!!
我不仅发现它非常难以理解,因为我仍然是 javascript 的业余爱好者,并且发现 js 已经足够困难了,jquery 的语法就像愚蠢地难以理解。

我确信无需使用 jquery 就可以实现我的目标。

有什么想法吗?所有帮助/评论/想法都非常感谢。
非常感谢。

I have a script that returns a list in alphabetical order as follows

<div id="x">
    <ul>
        <li>Apple
        <li>Banana
        <li>Blackberry
        <li>Blueberry
        <li>Cherry
        <li>Cranberry
    </ul>
</div>

However there are many items (almost 100) in the list and I am hoping to rearrange them as follows

<div id="x">
    <span id="A">A</span>
    <ul>
        <li>Apple
    </ul>
    <span id="B">B</span>
    <ul>
        <li>Banana
        <li>Blackberry
        <li>Blueberry
    </ul>
    <span id="C">C</span>
    <ul>
        <li>Cherry
        <li>Cranberry
    </ul>     
<div>

I'm not really sorting fruit btw, this is just an example.
It MUST be in that form, for reasons that matter not, I just need help creating and appending the span elements and the individual lists.
I have tried using inner/outer HTML and I'm finding it really really difficult. I currently have something like this:

function getAllLists()  
{  
var page = document.getElementById("x")
var allLists = page.getElementsByTagName("li");   
var num = allLists.length;  
//Some form of a for counter loop here
for (var counter = 0; counter < num; counter++) {   
    var first=allLists[counter].outerHTML;
    var second=allLists[counter+1].outerHTML;
    var firstletter= (allLists[counter].substring(0, 1)).toUpperCase();
    var secondletter= (allLists[counter+1].substring(0, 1)).toUpperCase();
    allLists[counter].outerHTML = '<span id="'+firstletter+'">'+firstletter+'</span>'+first;
    }
}

PLEASE PLEASE PLEASE PLEASE AVOID USING JQUERY.
I can't stress this enough!!
Not only do I find it extremely difficult to understand, as I am still an amateur at javascript and find js already difficult enough as it is, the syntax for jquery is like just stupidly hard to understand.

I am certain it is possible to achieve what I am aiming for WITHOUT the need to use jquery.

Any ideas? all help/comments/ideas are more than appreciated.
Many thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蹲在坟头点根烟 2024-12-25 02:33:17

首先忘记使用inner/outerHTML 操作DOM。它们可以方便地插入 HTML 块或文档部分,但它们绝对不适合一般的 DOM 操作。

使用 DOM 方法。

首先,将所有 LI 元素加载到一个数组中。然后使用排序函数对它们进行排序。然后将它们放回到用 UL 元素包裹的 DOM 中,并在每次第一个字母发生变化时用跨度分隔。

编辑

这是一个可以完成这项工作的函数。它对 lIs 进行排序,不确定是否真的需要。如果没有的话,这个功能就会变得简单很多。

<script type="text/javascript">

// Simple helper
function getText(el) {
  if (typeof el.textContent == 'string') {
    return el.textContent.replace(/^\s+|\s+$/g,'');
  }
  if (typeof el.innerText == 'string') {
    return el.innerText.replace(/^\s+|\s+$/g,'');
  }
}

function sortLIs(id) {
  // Get the element
  var el = document.getElementById(id);

  // Get the UL element that will be replaced
  var sourceUl = el.getElementsByTagName('ul')[0];

  // Get the LIs and put them into an array for sorting
  var nodes = sourceUl.getElementsByTagName('li');
  var li, lis = [];

  for (var i=0, iLen=nodes.length; i<iLen; i++) {
    lis[i] = nodes[i];
  }

  // Sort them
  lis.sort(function(a, b) {
    return  getText(a) > getText(b)? 1 : -1;
  });

  // Now put them into the document in different ULs separated
  // by spans.
  // Create some temporary elements for cloning
  var ul, ulo = document.createElement('ul');
  var sp, spo = document.createElement('span');
  var frag = document.createDocumentFragment(); // fragments are handy
  var firstChar, currentChar;

  // For each LI in the array...
  for (i=0; i<iLen; i++) {
    li = lis[i];
    firstChar = getText(li).substr(0,1) || '';

    // If first char doesn't match current, create a new span
    // and UL for LIs
    if (firstChar !== currentChar) {
      currentChar = firstChar;

      // New span
      sp = spo.cloneNode(false);
      sp.appendChild(document.createTextNode(firstChar.toUpperCase()));
      sp.id = firstChar;
      frag.appendChild(sp);

      // New UL
      ul = ulo.cloneNode(false);
      frag.appendChild(ul);
    }

    // Add the li to the current ul
    ul.appendChild(li);
  }

  // Replace the UL in the document with the fragment
  el.replaceChild(frag, sourceUl);
}

</script>


<div id="x">
    <ul>
        <li>Cherry
        <li>Banana
        <li>Apple
        <li>Blueberry
        <li>Cranberry
        <li>Blackberry
    </ul>
</div>

<button onclick="sortLIs('x');">Sort</button>

请注意,LI 仅移动到文档片段,并且原始 UL 被多个元素替换。我将 LI 打乱以表明排序是有效的。

编辑 2

如果您将数组作为文本,则:

var fruits = ['Cherry','Banana','Apple','Blueberry',
              'Cranberry','Blackberry'].sort();

function insertFruits(id) {
  var el = document.getElementById(id);

  // Check that the above worked
  if (!el) return;

  var frag = document.createDocumentFragment();
  var li, lio = document.createElement('li');
  var ul, ulo = document.createElement('ul');
  var sp, spo = document.createElement('span');
  var firstChar, currentChar;

  for (var i=0, iLen=fruits.length; i<iLen; i++) {
    fruit = fruits[i];
    firstChar = fruit.substr(0,1).toUpperCase();

    if (firstChar !== currentChar) {
      currentChar = firstChar;
      sp = spo.cloneNode(false);
      sp.appendChild(document.createTextNode(firstChar));
      sp.id = firstChar;
      frag.appendChild(sp);
      ul = ulo.cloneNode(false);
      frag.appendChild(ul);
    }
    li = lio.cloneNode(false);
    li.appendChild(document.createTextNode(fruit));
    ul.appendChild(li);
  }
  el.appendChild(frag);
}

Firstly forget all about manipulating the DOM using inner/outerHTML. They are handy for inserting chunks of HTML or sections of documents, but they are definitely not intended for general DOM manipulation.

Use DOM methods.

Firstly, load all the LI elements into an array. Then sort them using a sort function. Then put them back into the DOM wrapped in UL elements and separated by spans each time the first letter changes.

Edit

Here's a function that does the job. It sorts the lIs, not sure if that's really needed. If not, the function becomes a lot simpler.

<script type="text/javascript">

// Simple helper
function getText(el) {
  if (typeof el.textContent == 'string') {
    return el.textContent.replace(/^\s+|\s+$/g,'');
  }
  if (typeof el.innerText == 'string') {
    return el.innerText.replace(/^\s+|\s+$/g,'');
  }
}

function sortLIs(id) {
  // Get the element
  var el = document.getElementById(id);

  // Get the UL element that will be replaced
  var sourceUl = el.getElementsByTagName('ul')[0];

  // Get the LIs and put them into an array for sorting
  var nodes = sourceUl.getElementsByTagName('li');
  var li, lis = [];

  for (var i=0, iLen=nodes.length; i<iLen; i++) {
    lis[i] = nodes[i];
  }

  // Sort them
  lis.sort(function(a, b) {
    return  getText(a) > getText(b)? 1 : -1;
  });

  // Now put them into the document in different ULs separated
  // by spans.
  // Create some temporary elements for cloning
  var ul, ulo = document.createElement('ul');
  var sp, spo = document.createElement('span');
  var frag = document.createDocumentFragment(); // fragments are handy
  var firstChar, currentChar;

  // For each LI in the array...
  for (i=0; i<iLen; i++) {
    li = lis[i];
    firstChar = getText(li).substr(0,1) || '';

    // If first char doesn't match current, create a new span
    // and UL for LIs
    if (firstChar !== currentChar) {
      currentChar = firstChar;

      // New span
      sp = spo.cloneNode(false);
      sp.appendChild(document.createTextNode(firstChar.toUpperCase()));
      sp.id = firstChar;
      frag.appendChild(sp);

      // New UL
      ul = ulo.cloneNode(false);
      frag.appendChild(ul);
    }

    // Add the li to the current ul
    ul.appendChild(li);
  }

  // Replace the UL in the document with the fragment
  el.replaceChild(frag, sourceUl);
}

</script>


<div id="x">
    <ul>
        <li>Cherry
        <li>Banana
        <li>Apple
        <li>Blueberry
        <li>Cranberry
        <li>Blackberry
    </ul>
</div>

<button onclick="sortLIs('x');">Sort</button>

Note that the LIs are just moved to the document fragment and that the original UL is replaced by multiple elements. I've jumbled the LIs to show that the sort works.

Edit 2

If you have the array as text, then:

var fruits = ['Cherry','Banana','Apple','Blueberry',
              'Cranberry','Blackberry'].sort();

function insertFruits(id) {
  var el = document.getElementById(id);

  // Check that the above worked
  if (!el) return;

  var frag = document.createDocumentFragment();
  var li, lio = document.createElement('li');
  var ul, ulo = document.createElement('ul');
  var sp, spo = document.createElement('span');
  var firstChar, currentChar;

  for (var i=0, iLen=fruits.length; i<iLen; i++) {
    fruit = fruits[i];
    firstChar = fruit.substr(0,1).toUpperCase();

    if (firstChar !== currentChar) {
      currentChar = firstChar;
      sp = spo.cloneNode(false);
      sp.appendChild(document.createTextNode(firstChar));
      sp.id = firstChar;
      frag.appendChild(sp);
      ul = ulo.cloneNode(false);
      frag.appendChild(ul);
    }
    li = lio.cloneNode(false);
    li.appendChild(document.createTextNode(fruit));
    ul.appendChild(li);
  }
  el.appendChild(frag);
}
木格 2024-12-25 02:33:17

HTML:

<body>
  <div id="x">
    <ul>
        <li>Apple
        <li>Banana
        <li>Blackberry
        <li>Blueberry
        <li>Cherry
        <li>Cranberry
    </ul>
    <ul id="new"></ul>

JavaScript:

var list = document.querySelector('#x ul'),
    newUl = document.getElementById('new'),
    fruits = [],
    key = "A";

for(var i=0; i<list.children.length; i++){
  fruits.push(list.children[i].innerText);
}

fruits.sort();

for(var i=0; i<fruits.length; i++){
  if(key == fruits[i].split('')[0]){
    var span = document.createElement('span'),
        li = document.createElement('li');
    span.setAttribute('id', key);
    li.innerText = fruits[i];
    if(document.getElementById(key)){
      document.getElementById(key).appendChild(li);
    }
    else{
      span.appendChild(li);
      newUl.appendChild(span);
    }

  }
  if(fruits[i+1]){
    key = fruits[i+1].split('')[0];
  }
}

例子:

Live Code

HTML:

<body>
  <div id="x">
    <ul>
        <li>Apple
        <li>Banana
        <li>Blackberry
        <li>Blueberry
        <li>Cherry
        <li>Cranberry
    </ul>
    <ul id="new"></ul>

JavaScript:

var list = document.querySelector('#x ul'),
    newUl = document.getElementById('new'),
    fruits = [],
    key = "A";

for(var i=0; i<list.children.length; i++){
  fruits.push(list.children[i].innerText);
}

fruits.sort();

for(var i=0; i<fruits.length; i++){
  if(key == fruits[i].split('')[0]){
    var span = document.createElement('span'),
        li = document.createElement('li');
    span.setAttribute('id', key);
    li.innerText = fruits[i];
    if(document.getElementById(key)){
      document.getElementById(key).appendChild(li);
    }
    else{
      span.appendChild(li);
      newUl.appendChild(span);
    }

  }
  if(fruits[i+1]){
    key = fruits[i+1].split('')[0];
  }
}

Example:

Live Code

花桑 2024-12-25 02:33:17

好吧,这就是我完成它的方法:

var allLists, elements, item, lastLetter, lastUl, letter, page, span, _i, _len;

page = document.getElementById("x");
allLists = page.getElementsByTagName("li");
lastLetter = null;
lastUl = null;
elements = document.createDocumentFragment();

for (_i = 0, _len = allLists.length; _i < _len; _i++) {
  item = allLists[_i];
  letter = item.innerText[0].toUpperCase();
  if (letter !== lastLetter) {
    lastLetter = letter;
    span = document.createElement('span');
    span.innerText = letter;
    span.id = letter;
    elements.appendChild(span);
    lastUl = document.createElement('ul');
    elements.appendChild(lastUl);
  }
  lastUl.appendChild(item.cloneNode(true));
}

while (page.firstChild) page.removeChild(page.firstChild);

page.appendChild(elements.cloneNode(true));

请在此处查看此工作: http://jsfiddle.net/HjWhY/

Well, this is the way I get it done:

var allLists, elements, item, lastLetter, lastUl, letter, page, span, _i, _len;

page = document.getElementById("x");
allLists = page.getElementsByTagName("li");
lastLetter = null;
lastUl = null;
elements = document.createDocumentFragment();

for (_i = 0, _len = allLists.length; _i < _len; _i++) {
  item = allLists[_i];
  letter = item.innerText[0].toUpperCase();
  if (letter !== lastLetter) {
    lastLetter = letter;
    span = document.createElement('span');
    span.innerText = letter;
    span.id = letter;
    elements.appendChild(span);
    lastUl = document.createElement('ul');
    elements.appendChild(lastUl);
  }
  lastUl.appendChild(item.cloneNode(true));
}

while (page.firstChild) page.removeChild(page.firstChild);

page.appendChild(elements.cloneNode(true));

See this working here: http://jsfiddle.net/HjWhY/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文