Jquery文本限制而不删除活动标记

时间:2012-08-21 11:56:10

标签: jquery

我目前正试图通过使用以下Jquery来限制项目中某些动态标题的长度。

通过@Utkanos改进编辑

$(document).ready(function() {

$(function(){
  $(".newsTitle").each(function(i){
    var len=$(this).text().length;
    if(len>40) // If more than 35 characters then..
    {
      $(this).text($(this).text().substr(0,40)+'...'); // then add ...
      }
    });       
  });
});

我需要能够限制标题长度,但不要损坏标题周围的链接标签。这可能吗?这是我必须使用的HTML。

<h2 class="newsTitle">
    <a href="/blog/new-story">Lorem Ipsum ameh dolor sit loremip ipsum</a>
</h2>

1 个答案:

答案 0 :(得分:2)

变化:

$(".newsTitle")

为:

$(".newsTitle a")

这样你就可以正确地操作包含文本的节点,而不是它包含锚元素的父节点。

相关问题