0

我有以下创建多个具有 truncateMe id 的 div 块,我想截断此 div 中的内容。

<ul class="usernews">
    @foreach(var news in Model.News){
        <li>
                <div class="usernews_img">image</div>
                <div class="usernews_info">
                    <div class="truncateMe">@Html.Raw(@news.News.NewsContent)</div>
                </div>

        </li>
    }
</ul>

 <script type="text/javascript">

     var len = 100;
     var p = document.getElementById('truncateMe1');
     if (p) {

         var trunc = p.innerHTML;
         if (trunc.length > len) {

             /* Truncate the content of the P, then go back to the end of the
             previous word to ensure that we don't truncate in the middle of
             a word */
             trunc = trunc.substring(0, len);
             trunc = trunc.replace(/\w+$/, '');

             /* Add an ellipses to the end and make it a link that expands
             the paragraph back to its original size */
             trunc += '<a href="#" ' +
      'onclick="this.parentNode.innerHTML=' +
      'unescape(\'' + escape(p.innerHTML) + '\');return false;">' +
      '...<\/a>';
             p.innerHTML = trunc;
         }
     }

</script>

然后我有这个 java 脚本,它适用于具有 truncateMe id 的单个 div。我如何为每个具有 truncateMe id 的 div 应用相同的内容?

4

1 回答 1

1

如果你被允许使用 jQuery,这真的很容易。

$.fn.truncate = function(options) {
   options = $.extend({maxLength:100}, options);

   this.each(function() {
     var $this = $(this);

     var html = $this.html();

     if (html.length <= options.maxLength) return;

     html = html.substring(0, options.maxLength);
     html = html.replace(/\w+$/, '');

     html += '<a href="#" ' +
      'onclick="this.parentNode.innerHTML=' +
      'unescape(\'' + escape($this.html()) + '\');return false;">' +
      '...<\/a>';

     $this.html(html);
   });
}

然后使用它:

$('.truncate-me').truncate(); // use a CSS class instead of IDs
于 2012-05-18T04:41:21.023 回答