开发者

Making a list of every separate line with jQuery

开发者 https://www.devze.com 2022-12-18 17:51 出处:网络
I\'d love to know that how to create a list from block of text. Let me explain.. Here\'s my html: <div class=\"asd\">

I'd love to know that how to create a list from block of text. Let me explain..

Here's my html:

<div class="asd">
well
worth
it
</div>

And this should be automatically converted to list like this:

<div class="asd">
<ul>
<li>well</li>
<li>worth</li>
<li>it</li>
</ul>
</div>

Hope you understood :-D I've already tried it with various开发者_如何学运维 methods but I'm not familiar with jQuerys element-functions yet.

Martti Laine


Something like this should do the trick:

$(".asd").each(function() {
    var list = $("<ul>").insertBefore(this);
    var lines = $(this).remove().text().split("\n");
    list.append($.map(lines, function(str) {
        return $("<li>").text(str).get(0);
    })); 
});

You might want to add some kind of check for empty lines, though.

0

精彩评论

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