首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >截断具有特定名称的每个div中的文本

截断具有特定名称的每个div中的文本
EN

Stack Overflow用户
提问于 2019-07-08 08:21:06
回答 1查看 24关注 0票数 0

我想截断具有相同类名的多个div,目前我只能让它在第一次出现div时工作

我想截断具有相同类名的多个div,目前我只能让它在第一次出现的div上工作,而不是分别在每个div上工作。

代码语言:javascript
复制
var truncate = function (elem, limit, after) {
	if (!elem || !limit) return;
	var content = elem.textContent.trim();	
	content = content.split(' ').slice(0, limit);
	content = content.join(' ') + (after ? after : '');
	elem.textContent = content;
	
};

var elem = document.querySelector('.truncate');
truncate(elem, 20, '...');
代码语言:javascript
复制
<div class="truncate">
	Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.
</div>
<div class="truncate">
	Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.
</div>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-08 08:22:22

使用querySelectorAll并遍历它们:

代码语言:javascript
复制
var truncate = function(elem, limit, after) {
  if (!elem || !limit) return;
  var content = elem.textContent.trim();
  content = content.split(' ').slice(0, limit);
  content = content.join(' ') + (after ? after : '');
  elem.textContent = content;

};

const elems = [...document.querySelectorAll(".truncate")];
elems.forEach(elem => truncate(elem, 20, "..."));
代码语言:javascript
复制
<div class="truncate">
  Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.
</div>
<div class="truncate">
  Port tender gun spanker lanyard heave to topmast. Heave down draught piracy loaded to the gunwalls mizzenmast topsail Brethren of the Coast. Lanyard snow Jack Ketch swing the lead maroon spike black jack.
</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56927073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档