Rails 4 jQuery截断字符串

Rails 4 jQuery truncate string

本文关键字:字符串 jQuery Rails      更新时间:2023-09-26

想要实现(…)当文本长度大于150个字符时例如这是我的jQuery代码

jQuery(document).ready(function($){
  $("#content p").each(function(){
    if ($(this).text().length > 150) {
      $(this).text($(this).text().substr(0, 145));
      $(this).append('...');
    }
  });
});

this is my view

<div id="content">
  <p><%= job.job_description.html_safe %></p>
</div>

但问题是这个jQuery代码工作只是为第一个job_description为什么?

如果您使用像tinymce这样的文本编辑器,请尝试以下代码将html_safe变为

   <div class="content">
     <p><%= truncate(job.job_description, length: 170, escape: false).html_safe %></p>
   </div>

如果您不介意使用ruby,您可以使用truncate方法。

你可以试试这个:

truncate("Once upon a time in a world far far away")
# => "Once upon a time in a world..."
truncate("Once upon a time in a world far far away", length: 17)
# => "Once upon a ti..."
truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
# => "Once upon a..."
truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')
# => "And they f... (continued)"
truncate("<p>Once upon a time in a world far far away</p>")
# => "&lt;p&gt;Once upon a time in a wo..."
truncate("<p>Once upon a time in a world far far away</p>", escape: false)
# => "<p>Once upon a time in a wo..."
truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
# => "Once upon a time in a wo...<a href="#">Continue</a>"

为什么只有"第一"在javascript中工作的唯一原因在类似于你的情况下,你在DOM查询中使用元素的id是因为有多个DOM元素具有相同的id值。您需要确保DOM中的每个元素都具有唯一的id,这是DOM文档有效所必需的。

当使用id选择器时,返回具有id的第一个元素,而不管文档中具有相同id的元素的数量。当然,至少有一个具有id的元素必须出现在DOM中,否则选择器将找不到任何内容。

所以作为一个解决方案,你可以使用html class属性与这些元素相同的值。与id不同,class可以重复使用。

如下所示:

# In your view
<div class="content">
  <p><%= job.job_description.html_safe %></p>
</div>

# JQuery
jQuery(document).ready(function($){
  $(".content p").each(function(){
    if ($(this).text().length > 150) {
      $(this).text($(this).text().substr(0, 145));
      $(this).append('...');
    }
  });
});

@8bithero已经提到的另一种方法是,您可以使用Rails TextHelper#truncate来生成截断的文本,而根本不用担心javascript操作。使用这种方法,您可以摆脱javascript代码并将view更新为:

# In your view
<div class="content">
  <p><%= truncate(job.job_description, length: 150) %></p>
</div>