我想截断具有相同类名的多个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>
发布于 2019-07-08 08:22:22
使用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>
https://stackoverflow.com/questions/56927073
复制相似问题