开发者

Read More jQuery plugin failing with HTML

I'm using this code in order to show just the first 500 chars (and cut only after a complete word) of a text, but it fails apparently when it finds some HTML code in the "500" threshold.

In that case, it just adds the "..." and then continues the text (and it displays the "See More" link as well).

Eg:

Lorem <strong>impsum dolor</strong> sit amet. Etcétera.

Let's say it should cut the text between "impsum" and "dolor". The result is:

Lorem <strong>impsum...<span class="hidden" style="display:none;">dolor</span></strong> sit amet. Etcétera. <a href="#">See More</a>

It should be:

Lorem <strong>impsum... <span class="hidden" style="display:none;">dolor</strong> sit amet. Etcétera</span><a href="#">See More</a>

or...

Lorem <strong>impsum dolor</strong>... <span class="hidden" style="display:none;">sit amet. Etcétera</span<a href="#">See More</a>

Any way would be ok, I just want to cut the text after that. Is there any way to fix this?

Code:

(function ($) {
$.fn.readmore = function (settings) {

$('.home_excerpt').removeClass('home_excerpt');

var opts =  $.extend({}, $.fn.readmore.defaults, settings);

this.each(function () {
  $(this).data("opts", opts);
  if ($(this).html().length > opts.substr_len) {
    abridge($(this));
    linkage($(this));
  }
});

function linkage(elem) {
  elem.append(elem.data("opts").more_link);
  $(".text_seemore").click( function () {
    $(this).hide();
    $(this).siblings("span:not(.hidden)").hide().siblings("span.hidden").show();
    return false;
  });
}

function abridge(elem) {
  var opts = elem.data("opts");
  var txt = elem.html();
  var len = opts.substr_len;
  var dots = "<span>" +开发者_如何学运维 opts.ellipses + "</span>";
  var charAtLen = txt.substr(len, 1);
  while (len < txt.length && !/\s/.test(charAtLen)) {
      len++;
      charAtLen = txt.substr(len, 1);
  }
  var shown = txt.substring(0, len) + dots;
  var hidden = '<span class="hidden" style="display:none;">' + txt.substring(len, txt.length) + '</span>';
  elem.html(shown + hidden);
}

return this;
 };

  $.fn.readmore.defaults = {
substr_len: 500,
ellipses: '&#8230;',
more_link: '<br /><a href="#" class="text_seemore">See&nbsp;More</a>'
};

})(jQuery);


I just found this jquery plugin that works perfect with HTML tags:

http://plugins.learningjquery.com/expander/index.html


To get the first 500 chars of a string you can just do:

var result = myString.splice(0,500);

You may need to do some extra handling on the last word to see if it is a word of part of a word, then add your '...' and your 'read more' link.

NOTE: This example will remove the first 500 characters from the string myString and store them in result. myString will be left with the rest of the characters in the string.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜