0

我有一长串<li>s。下面的一段 JQuery 代码帮助我设置每个<li>. 请看这里

现在的问题是我不希望它将样式应用于最后一个<li>.

我可以这样做吗?

这是我的整个代码。请看一下

<html>

<script>
   $(document).ready(function(){
       $('li').each(function(){
       var $this = $(this), text=$this.text().trim(), words = text.split(/\s+/);
       var lastWord = words.pop();
       words.push('<span class="Red">' + lastWord + '</span>');
       $this.html(words.join(' '));
   });
});
</script>
<style>
.Red{color:red}
</style>
<body>
<li>my holy tag galore</li>
<li>my sandwich is balloney</li>
<li>the expected is not to be </li>
<li>oh REALLY? </li>

<script type="text/javascript" src="JQuery-1.10.2.js"></script>

</body>
</html>

非常感谢!

4

1 回答 1

0

我看到的唯一问题是您的“Red”和“Bold”类实际上可能没有真正定义。我自己测试了你的代码,它工作得很好——它将所说的类添加到最后一个词中。

但是,为了简单起见(嗯,好吧......为了 RegEx),您可以使用替换功能,就像这样:

$('li').click(function(){
    var $t = $(this);
    $t.html($t.text().trim().replace(/(\w+)[.!?]?\s*$/, "<b>$1</b>"));
});

<b></b>它用标签包围最后一个单词。只需将它们替换为您喜欢的任何内容即可。点击事件也是为了测试,你可以随时将其更改为each功能或其他任何东西,真的。

以下是有关此 RegEx 实际工作原理的细分:

https://stackoverflow.com/a/3648147/1368043

于 2013-09-22T23:20:40.337 回答