开发者

substr_len with HTML, show first X chars and a "See more" link (jquery.readmore Plugin)

I'm using a plugin to show only the first 500 characters of a text... But it's not working with some HTML, I can't reproduce it but I think it could have to be with an <img> tag, or a <blockquote> or maybe an <ul> / <ol>

It just shows the whole text AND the "See More" link...

Any idea?

This is the 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);


It seems that in your abridge() function you're trying to avoid cutting a word in half, if I'm reading your code right. The problem is that if there isn't any whitespace after the desired length, you will just return the whole thing, but you're not checking afterwards if that's the case. That means you will return the full text AND put the more link in too.

As you're processing HTML, the above is a usual case if you're having single word lines, tables with single word cells, etc., of if you're using &nbsp; as whitespace.

The bigger problem is that you're cutting the HTML as string, which will almost certainly result in broken markup. You can easily cut tags in half, strip block elements' closing tags, and so on. See if you can use elem.text() to process it as pure string, or if you want to keep the formatting, see if you can extract the first paragraph, or something similar.

You can of course implement some advanced method of checking and closing stripped tags, but it might not worth the trouble. I'd check if there's a plugin out there which already does what you need.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜