简体   繁体   中英

Single script for text truncation in multiple divs

This is continuation of my previous question .

Answer given by Joffrey worked fine But problem in that is, It loads the same content in all the divs which has the same class name.

This should work independently for each divs. If you check the demo attached, you can see all the divs are displaying the same content as first div even though each div has different content.

Here is the code used

var text = $('.truncate, .truncate_another').text();
    var shortText = $.trim(text).substring(0, 50).split(" ").slice(0, -1).join(" ") + "...";
    $('.truncate, .truncate_another').text(shortText);

    $('.truncate, .truncate_another').hover(function(){
        $(this).text(text);
        $('.truncate, .truncate_another').css('z-index', '10');
        $(this).css('z-index', '100');
    }, function(){
        $(this).text(shortText);
    });

DEMO Here

Setting properties to outcome of $('.truncate, .truncate_another') will, as you've noticed, affect every matching item. Loop over the items to handle them separately:

$('.truncate, .truncate_another').each(function() {
  var text = $(this).text();
  var shortText = $.trim(text).substring(0, 50).split(" ").slice(0, -1).join(" ") + "...";
  $(this).text(shortText);

  $(this).hover(function(){
    $(this).text(text);
    $('.truncate, .truncate_another').css('z-index', '10');
    $(this).css('z-index', '100');
  }, function(){
    $(this).text(shortText);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM