Javascript-P标记上的maxLength的循环

时间:2018-09-20 01:46:10

标签: javascript jquery loops for-loop maxlength

我这里有一个解决方案,将所选P标记的字符限制为125个字符,但是它仅适用于循环中的第一个子代,如何编辑以下代码以在For循环中工作?我已经尝试了一些使用jQuery的解决方案,但没有找到任何可行的方法。

感谢帮助!

function truncateText(selector, maxLength) {

    var element = document.querySelector(".hp-um-description")
     for (element = element) {
        var truncated = element.innerText;

        if (truncated.length > maxLength) {
            truncated = truncated.substr(0,maxLength) + '...';
        }
        return truncated;  
     }
    }

    $(".hp-um-description").each(function(){
      document.querySelector('.hp-um-description').innerText = truncateText('.hp-um-description', 125);
    });

3 个答案:

答案 0 :(得分:2)

您可以使用jQuery .text()来避免循环并相当干净地实现这一目标。

function truncateText(selector, maxLength) {
  $(selector).text((i, txt) => txt.length > maxLength ? txt.substr(0,maxLength) + "..." : txt);
};

truncateText(".hp-um-description", 100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="hp-um-description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris feugiat ipsum massa, et sagittis enim tempus id. Mauris nisl turpis, pellentesque scelerisque congue nec, faucibus vel arcu.</p>

<p class="hp-um-description"> Fusce id ultrices nibh. Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus.</p>

<p class="hp-um-description">Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus. Duis vehicula placerat sapien, ac consectetur dolor egestas eget.</p>

上面的代码将遍历选择器满足的所有元素并应用一个函数。此行确定是否应将其截断:

     txt.length > maxLength ?    txt.substr(0,maxLength) + "..."     :         txt
//(If length exceeds maxlength)     (truncate and add ...)         (else)    (leave the text as-is)

如果您还希望截断string,则可以改用以下代码:

String.prototype.truncate = function(maxLength) {
  var t = this.toString();
  return t.length > maxLength ? t.substr(0, maxLength) + "..." : t;
};

function truncateText(selector, maxLength) {
  $(selector).text((i, txt) => txt.truncate(maxLength));
};

//Truncate an existing element's text
truncateText(".hp-um-description", 100);

//Truncate a string
console.log("This is a long string that exceeds 30 characters.".truncate(30));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="hp-um-description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris feugiat ipsum massa, et sagittis enim tempus id. Mauris nisl turpis, pellentesque scelerisque congue nec, faucibus vel arcu.</p>

<p class="hp-um-description"> Fusce id ultrices nibh. Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus.</p>

<p class="hp-um-description">Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus. Duis vehicula placerat sapien, ac consectetur dolor egestas eget.</p>

答案 1 :(得分:0)

尝试以下代码:

function truncateText(element, maxLength) {
    var truncated = element.innerText;
    if (truncated.length > maxLength)
        truncated = truncated.substr(0,maxLength) + '...';
    return truncated;
}
$(function() {
    $(".hp-um-description").each(function(i,obj) {
        obj.innerText = truncateText(obj, 125);
    });
});

答案 2 :(得分:0)

在普通JavaScript中,您可以通过以下方式实现此目标...

var maxLength = 125;

/* select elements as an Array 
   and iterate with Array.forEach() */

[].slice.call(document.querySelectorAll(".hp-um-description")).forEach(function(el) {
    /* 'el' => each ".hp-um-description" element */

    /* attempt truncation */
    el.innerText = el.innerText.slice(0, maxLength);
    /* if el.innerText.length is shorter than
       'maxLength' the whole String will be returned (unchanged),
       otherwise the String will be truncated (modified) */
});

JQuery el函数中的.each()变量的等效项绑定到回调的this属性,就像这样……

$(".hp-um-description").each(function() {
    /* $(this) => each ".hp-um-description" element */

    var el = $(this);

    /* apply the same conditions as above */
    el.text( el.text().slice(0, maxLength) ); 
});

希望有帮助:D

请参阅: