Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何缩短自动过帐的文本长度_Javascript_Html_Css_Maxlength - Fatal编程技术网

Javascript 如何缩短自动过帐的文本长度

Javascript 如何缩短自动过帐的文本长度,javascript,html,css,maxlength,Javascript,Html,Css,Maxlength,我想缩短我文章中的文本,因为我使用IFTTT自动发布内容。。。 我试过这个 function truncateText(selector, maxLength) { var element = document.querySelector(selector), truncated = element.innerText; if (truncated.length > maxLength) { truncated = truncated.su

我想缩短我文章中的文本,因为我使用IFTTT自动发布内容。。。 我试过这个

function truncateText(selector, maxLength) {
    var element = document.querySelector(selector),
        truncated = element.innerText;

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

document.querySelector('p').innerText = truncateText('p', 30);

但它什么也做不了…

使用jQuery,您可以做到:

    function truncateText(selector, maxLength) {

        $(selector).each(function(){
            $(this).text($(this).text().substr(0,maxLength) + '...');
        });

    }


    truncateText("p",30);
或者在纯javascript中:

        function truncateText(selector, maxLength) { 
         var elemts = document.getElementsByTagName(selector); 
         for(var i = 0; i < elemts .length; i++) {
              elemts[i].innerHTML =  elemts[i].innerHTML.substr(0,maxLength) + '...'; 
            }
        }
函数truncateText(选择器,maxLength){
var elemts=document.getElementsByTagName(选择器);
对于(变量i=0;i
我在JSFIDLE上尝试了您的代码,它正在工作。 可能的解决方案是在页面加载后使用代码

第一个解决方案

脚本
标记移到末尾,就在关闭
标记之前

第二种解决方案

等待页面,然后使用您的代码

function truncateText(selector, maxLength) {
    var element = document.querySelector(selector),
    truncated = element.innerText;

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

document.addEventListener("DOMContentLoaded", function(event) { // After the page is loaded
       document.querySelector('p').innerText = truncateText('p', 30);
});