简体   繁体   English

用于多个div中文本截断的单个脚本

[英]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. Joffrey给出的答案很好,但是问题在于,它在所有具有相同类名的div中加载相同的内容。

This should work independently for each divs. 对于每个div,这应该独立工作。 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. 如果检查所附的演示,则可以看到所有div都显示与第一个div相同的内容,即使每个div具有不同的内容。

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. 您已经注意到,将属性设置为$('.truncate, .truncate_another')将影响每个匹配项。 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);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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