如果超过10个字符长度收缩文本

问题描述:

嗨我有以下<h2>“示例示例示例”。我想检测这个<h2>的长度,如果它超过10个字符,缩小它为“示例ex ...”。得到它?将其缩小为10个字符并将“...”添加到最后。如果超过10个字符长度收缩文本

这里是我的代码:

HTML

<h2>Example example example example example</h2> 
<h2>Example</h2> 

jQuery的

$(document).ready(function(){ 
    var dtl = $('.h2').text().length; 

     if(dtl>10){ 
     $('.h2').text().length = 10; 
     $('.h2').text($('.h2').text()+"..."); 
    } 
}); 

但是,这不工作...

+0

我不是谁downvoted你的人,但如果人们不喜欢这个问题,我的猜测是,那是因为你基本上是要求其他人写的代码你。 – 2015-04-01 17:15:18

+1

是什么?我发布的代码,我试过了,看看这个:http://stackoverflow.com/questions/815146/how-can-i-get-the-length-of-text-entered-in-a-textbox-using-jquery ,它有90多个upvotes?有人在这里讨厌我,并降低了我的所有帖子.. – pedritoalfonso 2015-04-01 17:16:34

+1

你想截短文本时,它*少于10个字符?这听起来反直觉。 – showdev 2015-04-01 17:18:08

您需要在这种情况下使用SUBSTR:

而且你h2标签元素,而不是.h2类名。

$(document).ready(function(){ 
    var dtl = $("h2").text().length; 

    if(dtl>10){ 
     $('h2').text($('h2').text().substr(0,10)+"..."); 
    } 
}); 

我只是为了一个元素,您可能需要使用$("h2").each()来定位所有元素。

更完整代码:

$(document).ready(function(){ 

     $("h2").each(function() { 
      if($(this).text().length > 10) { 
       $(this).text($(this).text().substr(0,10)+"..."); 
      } 
     }); 
    }); 

DEMO

$(document).ready(function(){ 
 

 
    $("h2").each(function() { 
 
     if($(this).text().length > 10) { 
 
      $(this).text($(this).text().substr(0,10)+"..."); 
 
     } 
 
    }); 
 
});
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script> 
 
    <meta charset="utf-8"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body> 
 
<h2>Example example example example example</h2> 
 
<h2>Example</h2> 
 
</body> 
 
</html>

+0

这很好,它很短,谢谢! – pedritoalfonso 2015-04-01 17:23:24

+0

不客气:) – mohamedrias 2015-04-01 17:24:30

你有两个<h2>标签,你将不得不使用

$("h2").each(function() { 
    var dtl = $(this).text().length; 
    //rest of your code goes here 
    if(dtl>10){ 
     var res = $(this).text(); 
     res = res.substring(0, 4); //apply your logic here what ever you want pass (0, 10) 
    $(this).text(res +"..."); 
    } 
}); 
+0

这不是问题.. – pedritoalfonso 2015-04-01 17:17:12

+0

它解决了你的问题知道 – 2015-04-01 17:19:13

+0

重新编辑错过了 – 2015-04-01 17:21:09

试试这个代码,它可能工作

<h2>This tag contains more than 10 characters</h2> 

的Jquery:

$(document).ready(function() { 
     var len = $("h2").text().length; 
     var text = $("h2").text(); 

     if (len > 10) { 
      var stext = text.substring(0, 10); 
      $("h2").text(stext).append("..."); 
     } 

    });