javascript - 用于在多个 div 中 chop 文本的单个脚本

标签 javascript jquery html css

这是我的 previous question 的延续.

Joffrey 给出的答案工作正常但问题是,它在所有具有相同类名的 div 中加载相同的内容。

这应该对每个 div 独立工作。如果您查看随附的演示,您可以看到所有的 div 都显示与第一个 div 相同的内容,尽管每个 div 的内容不同。

这里是使用的代码

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

最佳答案

如您所见,将属性设置为 $('.truncate, .truncate_another') 的结果会影响每个匹配项。遍历元素以分别处理它们:

$('.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);
  });
});

关于javascript - 用于在多个 div 中 chop 文本的单个脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25377476/

相关文章:

javascript - 如何使用 forEach 循环访问对象属性?

jQuery - 将值从一个输入传递到另一个输入

html - 是否可以专门要求用户使用 HTML5 上传图片?

html - 无法让视频在同一个 <div> 容器中落后于图像

html - Div 宽度百分比在 CSS 中不起作用

javascript - Angular md-input-container 调整大小

javascript - 检查indexeddb createIndex是否成功

javascript - infinity.js 的最佳实践

javascript - 在 jQuery DataTables 中使用 sDom 删除搜索框

jQuery - 仅附加文本一次