【问题标题】:Truncating text within every div with a particular name截断具有特定名称的每个 div 中的文本
【发布时间】:2019-07-08 00:21:05
【问题描述】:

我想截断具有相同类名的多个 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>

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    使用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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-05
      • 2013-08-20
      • 2013-10-18
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      相关资源
      最近更新 更多