0
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
    </script>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>

<script type="text/javascript">
$(function()
{
        $("p").text(function(index, oldText) {
                return "Existing text: " + oldText + ". New text: A dynamically set text (#" + index + ")";
        });
});
</script>

结果:

Existing text: Paragraph 1. New text: A dynamically set text (#0)

Existing text: Paragraph 2. New text: A dynamically set text (#1)

Existing text: Paragraph 3. New text: A dynamically set text (#2)

问题:

如果我只想将其应用于第 1 段和第 2 段(以下是我想要的结果),我该怎么办?

Existing text: Paragraph 1. New text: A dynamically set text (#0)

Existing text: Paragraph 2. New text: A dynamically set text (#1)

Paragraph 3.
4

1 回答 1

1

您可以使用:lt(index)选择器获取小于特定索引的元素(0 索引,因此此处为 2 用于指定小于第 3 个元素)。

$("p:lt(2)").text(function(index, oldText) {

演示

于 2013-07-08T04:04:54.530 回答