jquery to add ids to all paras to make them all li

2019-09-09 12:06发布

I have a site with thousands of htm documents on them. Sometimes I need to send someone to a specific paragraph to read. What I am looking for is a jquery plugin which simply adds ids to all the paragraphs, making them linkable, so we could send them to: http://www.demo.com/index.html#p_10 for instance.

2条回答
淡お忘
2楼-- · 2019-09-09 12:48

Why a plugin? And no need for an ID

This should work if you insert a script into the page or into an existing external script

NOTE: This does NOT modify the DOM in any way and is WAY faster than an .each

$(function() {
  var pIndexPos = location.hash.indexOf("p_");
  if (pIndexPos!=-1) {
    var pIndex = parseInt(location.hash.substring(pIndexPos+2),10)+1; // 1based for nth
    var offsetTop = $("p:nth-child("+pIndex+")").offset().top-20; // - height of item
    $('html, body').animate({
      scrollTop: offsetTop
    },500);
  }
}); 
查看更多
祖国的老花朵
3楼-- · 2019-09-09 12:51

I think what you want is just a simple code like this

jQuery(document).ready(function() {
    jQuery('p').each(function(index, value) {
        value.id = '_p' + index;
    });

    $('html, body').animate({
        scrollTop: $(window.location.hash).offset().top
    }, 500);
});

Here is an example that also displays the id set.

http://jsfiddle.net/ekftprLt/2/

查看更多
登录 后发表回答