jQuery - 获得第一段

时间:2011-10-18 10:50:47

标签: javascript jquery

我有以下代码

<div class="side-box">
    <h1>Main Title</h1>
    <h2>Secondary Title</h2>
    <p>
        This is paragraph 1<br><br>
        This is paragraph 1<br><br>
        This is paragraph 3<br><br>
</div>

我正在尝试编写一个jQuery函数,它将显示第一段中的任何内容,然后在单击“read more”链接时显示其余部分。

内容由WYSIWYG编辑器生成,否则我确信自己可以创建此功能。

5 个答案:

答案 0 :(得分:4)

$('.side-box > p').not(':first-child').hide();

但你的代码中没有超过1个段落,你的意思是在第一次休息后(br)吗?


您可以使用以下方法删除第一个BR后的所有内容:

var str = $('.side-box p').html();
var substr = str.split('<br>');
$('.side-box p').html(substr[0]);

它搜索P,并用BR标签分割。

然后我们进行第一次拆分并用它替换p内容:)

答案 1 :(得分:1)

更新:

我只是注意到p标签意义上的段落不是 段落(在标记中定义了一个段落) - 尽管你要求的仍然是可能的,在编辑器中修改内容的方式可能是一个更好的考虑因素。


以下应该做的事情......

var paragraph = $("p:eq(0)").html();

虽然您可能希望使用html()text()val()来电,但我从来没有第一次使用正确的电话。

答案 2 :(得分:0)

为所有段落添加“显示链接”并隐藏段落本身:

var paragraphs = $(".side-box > p");
paragraphs.before(function () {
    return $("<a>Read more</a>").click(function () {
        // hide the "Read more" link. Alternatively, use .remove() to remove the link
        $(this).hide();
        // this link was inserted before the paragraph, so displaying the next element
        // (= paragraph)
        $(this).next().show();
    });
});
// hide the paragraphs which are now preceded by a "Read more" link
paragraphs.hide();

Example on JSFiddle

答案 3 :(得分:0)

示例working with your current HTML

$('.side-box p').first().each(function(i,e){
    htmlchunks = $(this).html().split('<br><br>');
    first_part = htmlchunks.shift();
    secondpart = $('<div class="hidden"/>').hide().html(htmlchunks.join('<br><br>'));
    $(this).html(first_part + '<a class="readmore">read more</a>').append(secondpart);
});

$('.readmore').click(function(){
    $(this).next('.hidden').show();
    $(this).detach();
});

但是,感谢。

答案 4 :(得分:0)

您可以使用CSS(IE&gt; = 9,因为第一个类型) - 这里的参考检查支持 - Can I Use first-of-type

.side-box p:first-of-type ~ * {
    display:none;
}

〜combinator分隔两个选择器,并且仅当第二个元素前面有第一个元素时才匹配第二个元素,并且它们共享一个公共父元素。 (IE 7+)

General sibling selectors documentation