【问题标题】:Trying to print paragraphs in div line by line while giving content limit to characters in div尝试在 div 中逐行打印段落,同时对 div 中的字符进行内容限制
【发布时间】:2017-06-06 05:26:57
【问题描述】:

您好,当 div 中的内容限制为 15 个字符时,我尝试在 div 中逐行打印段落,但它并排打印所有段落我如何逐行打印。这是我的代码

<script>
    $(document).ready(function() {
      $("div").text(function(index,currentText) {
        return currentText.substr(0, 15);
      });
    });

   <?php
         echo "<div>";
         for($i=0;$i<3;$i++){
             $key=array('helloss','howaree','welcomes','whkkky','getkkk');
             $random_key= array_rand($keywords); 
             $keys ="<p>" . $key[$random_key]  . $key[$random_key] . "</p>";
             echo $keys; 
           }
             echo "</div>";
  ?>

假设div中的15个字符是

   hellosshowaree
   h

应该如上所示,因为div 中应该只有 15 个字符,但如下所示

 hellosshowareeh

【问题讨论】:

  • hellosshowareeh 是 15 个字符......我不确定我是否理解......你能发布浏览器中显示的 HTML
  • 您可以在每个&lt;p&gt; 之后使用&lt;br /&gt; 换行

标签: javascript jquery html limit paragraph


【解决方案1】:

只需按如下方式更改您的 Javascript 编码

 var myDiv = $('#your-div-id');
 myDiv.text(myDiv.text().substring(0,16))

【讨论】:

  • 但那将是 16 个字符 - OP 想要 15 个 - 而他的 div 没有 id
  • 将所有段落并排组合在一起
【解决方案2】:
var txt= $('div').text();
if(txt.length > 15)
 $('div').text(txt.substring(0,15));

【讨论】:

    【解决方案3】:
    return currentText.substr(0, 14);
    

    使用 0 到 14 的范围,因为它们是 15 个字符。 使用 0 到 15 使其成为 16 个字符,这就是字符串中包含额外 h 的原因。 我猜就是这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-23
      • 2011-01-16
      • 2021-05-22
      • 1970-01-01
      • 2021-09-13
      相关资源
      最近更新 更多