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

时间:2019-07-08 00:21:05

标签: javascript html

我想截断具有相同类名的多个div,目前我只能使其在div的第一次出现时起作用

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

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, '...');
<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>

1 个答案:

答案 0 :(得分:0)

使用querySelectorAll并遍历它们:

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, "..."));
<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>