2012-05-18 4 views
0

truncateMe ids를 사용하여 div 블록을 여러 개 만들고이 div 내에서 내용을 잘라내려고합니다.동일한 ID 또는 클래스를 사용하여 여러 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> 

그런 다음 truncateMe id가있는 단일 div에서 작동하는이 Java 스크립트가 있습니다. truncateMe ID를 사용하여 모든 div에 대해 어떻게 적용 할 수 있습니까?

답변

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 
+0

내가 그것을 시도를 제공 할 것입니다. 감사합니다 :) – DarthVader

+0

사실이 줄에 구문 오류가 발생합니다.'options = $ .extend ({maxLength = 100}, options);'약 불평 = 기호 – DarthVader

+0

오류, 몇 가지 오류가 발생했습니다. 내 대답 – HackedByChinese

관련 문제