2

在我的 Wordpress 页面中,我有许多以歌词为主题的帖子。我希望以不同的方式设计交替的歌词。到目前为止,我已经整理了基础知识,但是我需要帮助使用 jQuery 为每行歌词添加前缀和后缀<li><ul>以便使用 CSS 样式将样式应用于奇数行和偶数行,正如我在这篇文章中看到的那样(http://stackoverflow .com/questions/358350/alternate-background-colors-for-list-items)。我的 HTML 当前如下所示:

<div id="lyricstext" style="overflow: auto; height: 340px; width: 640px;">
<ul>
Leave me alone
Leave me alone
Leave me alone
So just leave me alone
I said leave me alone
Leave me alone
Leave me alone
I’m not in the mood!
Piss off!
So when I say leave me alone
Nah T don’t play
I’m like Michael Jackson in a non-paedo way
The thought of mad partyin’, debauchery tortures me
My T-shirt reads “Fuck off and don’t talk to me”
Approaching every situation awkwardly
Like I’m mesmerized under some sort of sorcery
Who’s calling me? Don’t know – I’ll ignore it G
If I don’t share my time then is there more for me?
</ul>
</div>

所以,我想知道要在页面上应用什么 JS 来为我插入这些<li></li>标签,以便能够以不同的方式设置每个备用行的样式。谢谢

4

3 回答 3

3

你可以这样做 :

$('#lyricstext ul').html($('#lyricstext ul').html().split('\n').map(function(v){
    return '<li>'+v+'</li>';
}));​​​​​​​​​​​​​​​​

示范

如果你有多个 ul 你需要类似的东西

$('#lyricstext ul').each(function(){
    $(this).html($(this).html().split('\n').map(function(v){
       return '<li>'+v+'</li>';
    }));
});

当然,就像应用在 DOM 上的几乎所有代码一样,它必须在 DOM 准备好之后调用。所以你必须将你的代码包装在一个准备好的回调中;

$(function(){
    $('#lyricstext ul').html($('#lyricstext ul').html().split('\n').map(function(v){
        return '<li>'+v+'</li>';
    }));​​​​​​​​​​​​​​​​
});

​​​​​​​​​​​​​​​​​​​​</p>

于 2012-12-09T18:31:37.433 回答
1

你可以使用这样的函数:

var html = $('#lyricstext ul').html().split('\n').map(function(text){
    return '<li>'+text+'</li>';
});
$('#lyricstext ul').html(html);​​​​​​​​​​​​​​​​
于 2012-12-09T18:32:45.543 回答
0

很简单,试试这个:

var $ul = $("#lyricstext ul");
var lines = $ul.text().split('\n');

$.each(lines, function() {
    $ul.append('<li>' + this + '</li>');
    $ul.find('li:odd').addClass('alternate');
});​
于 2012-12-09T18:43:26.713 回答