开发者

jquery add text and anchor link to paragraph

开发者 https://www.devze.com 2023-02-04 13:44 出处:网络
Hi I have the following jQuery code that splits some content after the second paragraph, adds some other content in between, then displays the rest of the content at the end.

Hi I have the following jQuery code that splits some content after the second paragraph, adds some other content in between, then displays the rest of the content at the end.

jQuery('#bookDescription > p').slice(2).appendTo('#bookDescription');

I need to add a read more link at the end of that second paragraph that will link to and anchor link on the 3rd paragraph. Normally this would be easy to set up with just html but not sure how I can accomplish this with jQuery.

So, right now I have something like this (accomplished by jQuery above:

Paragraph One
Paragraph Two
Oth开发者_如何学JAVAer content 
Paragraph Three
Paragraph ....

And I want to add:

Paragraph One
Paragraph Two ... Red More
Other content 
<a name="linkFromReadMore"></a>Paragraph Three
Paragraph ....


you could do something like this:

$('p:nth-child(2)').append($('<a>', {
    'href': '#more',
    'html': '&hellip;read more'
})).after($('<p>', {
    'html': 'other content'
})).next().next().prepend($('<a>', {
    'name': 'more'
}));

demo


If you know the p elements, you can use .after() http://api.jquery.com/after/ or before(). So you can insert after or before. Creating new siblings of the same parent.


Using named anchors is a bit old-school these days. You can link to any point in the page by using its id.

So, knowing that, a better way might be to grab all but the first two paragraphs, like you're doing, and put them into another div:

var $more = $('<div></div>', {
    id : 'linkFromReadMore'
});

$('#bookDescription > p').slice(2).appendTo($more);

$('#bookDescription')
    .append(/* whatever you want in-between */)
    .append($more)
;
0

精彩评论

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