2009-10-07 7 views
2

나는 텍스트로 가득 찬 varchar 필드를 가지고 있으며, 텍스트의 100 자짜리 발췌 문장을 보여줄 수 있고 끝에 "Read More ..."링크를 보여주고 싶습니다. 스 니펫의 사용자가 "자세히보기 ..."를 클릭하면 페이지가 확장되어 나머지 텍스트가 표시됩니다.더 많은 링크가있는 발췌 텍스트 만들기

'표시/숨기기'기능을 jQuery와 함께 할 수있을 것 같아요. 그러나 ASP에 효과적으로 2 개의 텍스트의 varchar 필드를 분할하는 기능이 있다면 잘 모르겠습니다.

내 콘텐츠는 현재;

<%=StripHTML(rspropertyresults.Fields.Item("ContentDetails").Value)%> 

이 기능을 사용하여 HTML 태그를 제거합니다.

<% 
Function stripHTML(strHTML) 
    ''Strips the HTML tags from strHTML 

    Dim objRegExp, strOutput 
    Set objRegExp = New Regexp 

    objRegExp.IgnoreCase = True 
    objRegExp.Global = True 
    objRegExp.Pattern = "<(.|\n)+?>" 

    ''Replace all HTML tag matches with the empty string 
    strOutput = objRegExp.Replace(strHTML, "") 

    ''Replace all <and> with &lt; and &gt; 
    strOutput = Replace(strOutput, "<", "&lt;") 
    strOutput = Replace(strOutput, ">", "&gt;") 

    stripHTML = strOutput ''Return the value of strOutput 

    Set objRegExp = Nothing 
End Function 
%> 
+3

랩 디스플레이로 설정 한 스타일로 즉시 span 태그에 표시 할 텍스트가 아닌, : 없음. onclick으로 "Read More ..."주위에 ahref 태그를 추가하여 span 태그의 가시성을 토글합니다. –

+0

감사합니다. 데이터베이스의 각 레코드에 대해 얼마나 많은 세부 사항이 추가되는지 정확하게 알지 못하기 때문에 텍스트를 먼저 동적으로 분할하는 방법이 필요하다고 생각합니다. – doubleplusgood

답변

12

시작 지점으로 사용해보십시오. 하나는 처음 100 개 문자 ("visibleText")를 개최 한 나머지 ("textToHide")를 개최 :

<p> 
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas massa lectus, pulvinar vel scelerisque eget, 
    rutrum et nisi. Mauris semper viverra lorem sit amet faucibus. Fusce egestas metus sit amet lectus interdum 
    sollicitudin. Maecenas accumsan metus scelerisque tortor lobortis et pretium nibh cursus. 
</p> 
<script type="text/javascript"> 
    $(function() { 
     var textToHide = $('p').text().substring(100); 
     var visibleText = $('p').text().substring(1, 100); 

     $('p') 
      .html(visibleText + ('<span>' + textToHide + '</span>')) 
      .append('<a id="read-more" title="Read More" style="display: block; cursor: pointer;">Read More&hellip;</a>') 
      .click(function() { 
       $(this).find('span').toggle(); 
       $(this).find('a:last').hide(); 
      }); 

     $('p span').hide(); 
    }); 
</script> 

그래서 내가 여기했던 두 가지 변수를 만드는 것입니다.

그런 다음 jQuery에 모든 단락 태그 (더 구체적인 선택기를 정의하려는 경우)를 찾고, span 태그에 텍스트를 줄 바꿈하고 다시 모든 내용을 표시된 텍스트에 배치하고 끝에 링크를 추가하십시오 우리가 숨길 텍스트를 보여주기 위해 클릭 이벤트를 할당해야합니다.

클릭 기능은 단락의 모든 스팬 태그를 찾고 표시되도록 토글합니다 (여기서는 show() 기능이 더 적합 할 수 있음). 그리고 "더 읽기"링크를 숨 깁니다.

마지막으로 단락의 span 태그가 숨겨지기 시작했는지 확인합니다. 실제로 CSS 규칙 (p span {display: none;})을 만들면 텍스트가 숨김 상태로 시작되지만 JavaScript보다 빠르게 처리됩니다. jQuery show() 함수는 여전히 호출 될 때 해당 CSS 규칙을 무시합니다.

그렇게해야합니다.

+0

감사합니다. Phil. 나는 당신의 솔루션을 약간 수정했다. div에 ContentDetail을 래핑하고 단락보다는 div에 click 이벤트를 설정했다. 그게 작동되면,하지만 누군가가 텍스트를 확장 할 때 더 많은 링크를 읽고 더 많은 링크를 숨길 수있는 방법이 있는지 궁금 해서요? 또는 예를 들어 텍스트를 접는 링크를 더 읽으십시오. – doubleplusgood

+0

매우 간단하고 똑똑한 솔루션과 또한 좋은 설명 ... 감사합니다 :) – Bongs

+1

하지만 우리는 어떻게 클릭하면 더 많은 제목을 변경할 수 있습니다. 내가 그것을 클릭하면 더 많이 쓸 것입니다. 더 적은 & 다시 읽으십시오. 그 반대도 마찬가지입니다. –

0

당신이 한 모든 것은 할 수 있고, 당신이 그것에 대해 머리를 갖게되면 아주 쉽습니다. 나는 jquery 남자가 아니야 (Mootools for me!) 그래서 너를 도울 수 없어.

ASP 잘림 기능을 사용하려면주의해야합니다. html을 없애거나 닫지 않은 태그를 열어 둘 수있는 올바른 아이디어가 있습니다 (닫히지 않은 div 또는 스크립트 태그는 레이아웃을 엉망으로 만들 수 있습니다).

나는 것 :

  • 스트립이 처음
  • 길이는 그냥
  • 다른 현명한 이용 왼쪽 (your_string, 300)에 만 잡아 표시하여 절단하고 싶었보다 작은 경우 처음 300 자 (예)를 입력 한 다음 끝에 "..."을 추가하십시오. 멋지고 쉽습니다.

당신은 공상을 얻으 려하고 다음 공간에서 분리하려고 시도 할 수 있습니다.하지만 절반으로 단어를 자르지는 못하지만 VBScript에서 어떻게 할 지 머리 위로 올리는 것을 기억할 수는 없습니다. JS 아무 문제 없어!

1

필러 휠러의 샘플을 확장하면 jQuery의 Each 기능을 사용하여 테이블의 모든 td 요소에이를 적용하는 예가 있습니다.

<html> 
<head> 
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js" 
      type="text/javascript"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $("td").each(
       function(intIndex) { 
        var textToHide = $(this).text().substring(100); 
        var visibleText = $(this).text().substring(1, 100); 

        $(this) 
         .html(visibleText + ('<span>' + textToHide + '</span>')) 
         .append('<a id="read-more" title="Read More" style="display: block; cursor: pointer;">Read More&hellip;</a>') 
         .click(function() { 
          $(this).find('span').toggle(); 
          $(this).find('a:last').toggle(); 
         }); 

        $(this).find("span").hide(); 
       } 
      ) 

     }); 
    </script> 
</head> 
<body> 
    <table border="1"> 
     <tr> 
      <td> 
       "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." 
      </td> 
      <td> 
       "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" 
      </td> 
     </tr> 
    </table> 
</body> 

관련 문제