这是我的 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);
});
最佳答案
如您所见,将属性设置为 $('.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/