I'm trying to split an unordered list into two columns by finding the halfway point of the list and adding </ul><ul> after that </li>. This could be the complete wrong way to do this but it is how I thought to do it. My js looks like this:

我试图将无序列表拆分为两列,方法是找到列表的中点,然后在之后添加

    。这可能是完全错误的做法,但我就是这么想的。我的js是这样的:

$('.container ul').each(function(){

    var total = $(this).children().length;
    var half = Math.ceil(total / 2) - 1;
    $(this).children(':eq('+half+')').after('</ul><ul>');

});

The problem I'm having and what I don't understand is that .after() is reversing the order of the tags and outputs:

我所遇到的问题和我不理解的是。after()颠倒了标签和输出的顺序:

<ul>

< ul >

<li><a href="#">link</a></li>

<李> < a href = " # " > < / > < /李>链接

<li><a href="#">link</a></li>

<李> < a href = " # " > < / > < /李>链接

<li><a href="#">link</a></li>

<李> < a href = " # " > < / > < /李>链接

<ul></ul>

< ul > < / ul >

<li><a href="#">link</a></li>

<李> < a href = " # " > < / > < /李>链接

<li><a href="#">link</a></li>

<李> < a href = " # " > < / > < /李>链接

</ul>

< / ul >

Please let me know if there's a better way to do this, but I really would like to know why .after() is reversing the order of tags. Thanks

请让我知道是否有更好的方法,但是我真的很想知道为什么.after()颠倒了标签的顺序。谢谢

2 个解决方案

#1


7

You can't think about DOM modification as if you were editing the original HTML file. Once the browser has parsed the HTML file, to all intents and purposes it no longer exists. The only thing that matters is the DOM representation.

您不能像编辑原始HTML文件那样考虑DOM修改。一旦浏览器解析了HTML文件,实际上它就不存在了。唯一重要的是DOM表示。

With that in mind, let's have a look at the bit of code you've posted...

考虑到这一点,让我们看一下您发布的代码……

.after('</ul><ul>')

You're imagining this editing the HTML present and adding in a closing tag and an opening tag. It doesn't. It builds a document fragment from that code and then adds it as a sibling of the element in the original selection. Since </ul> isn't a valid beginning to a string of HTML, it is dropped. All you have left is <ul>, which is parsed as an element in its entirety (imagine an HTML document that went <div><ul></div> and you'll get the idea). So an empty ul element is inserted into the list as a sibling of the element you've selected: it's represented as <ul></ul> as this is the way to serialise a ul element to HTML.

您正在想象编辑HTML present并添加一个结束标记和一个开始标记。它不是。它从该代码构建一个文档片段,然后将其作为元素在原始选择中的兄弟元素添加。因为不是HTML字符串的有效开头,所以它被删除。您所剩下的就是