2008-12-29 69 views
1

我有一段文本,我希望顯示截斷,但單擊時它會展開顯示其餘部分。再次點擊應該截斷它。使用JQuery處理切換的onclick

我試圖用onclick事件來處理這個情況如下(警告:請勿在沒有閱讀下面的內容運行下面的代碼...):

<span id='blah' onclick='showAllComment("this is a long comment to see it all", 9, true)'>this is a...</span> 

<script> 
function showAllComment(comment, shortCommentLen, showFullComment) 
{ 
    alert($("#blah").html()); 

    if(showFullComment) 
    { 
     $("#blah").html(comment); 
     $("#blah").click(showAllComment(comment, shortCommentLen, false)); 
    } 
    else 
    { 
     $("#blah").html(comment.substring(0, shortCommentLen) + "..."); 
     $("#blah").click(showAllComment(comment, shortCommentLen, true)); 
    } 
} 
</script> 

,但是你會看到,它反覆自己調用,你必須結束任務瀏覽器(所以要小心運行此代碼!!!!)

任何人都可以建議爲什麼發生這種情況,以及如何解決它。

在此先感謝

+0

some 2008-12-29 13:33:37

+0

好點,但我不認爲截斷評論實際上是一個'縮寫',它會濫用標籤的最純粹的定義我認爲,什麼是任何人都認爲,這是最純粹的? – Dan 2008-12-30 11:55:40

回答

3

這是因爲你被遞歸調用showAllComment功能

試着做這樣的事情,而不是:

function showAllComment(comment, shortCommentLen, showFullComment) 
{ 
    alert($("#blah").html()); 

    if(showFullComment) 
    { 
     $("#blah").html(comment); 
     $("#blah").click(function() { showAllComment(comment, shortCommentLen, false);}); 
    } 
    else 
    { 
     $("#blah").html(comment.substring(0, shortCommentLen) + "..."); 
     $("#blah").click(function() {showAllComment(comment, shortCommentLen, true);}); 
    } 
} 

這樣,你是封閉的匿名內部調用函數,所以一旦你點擊了#bla元素,它就會被執行。

+0

當然,非常感謝Dreas。不過,我剛剛注意到這個解決方案的一個問題。 JQuery並沒有替代綁定事件,它添加到它,所以你得到越來越多的功能被稱爲每次它的點擊。使用DOM工作正常:document.getElementById(「blah」)。onclick = function(){...}; – Dan 2008-12-30 11:49:16

2

未啓用javascript的用戶將無法閱讀評論。更好的辦法是包括在span整個註釋,使JavaScript的截斷它在頁面加載時:

的javascript:

$(function() { 
    $(".blah").each(function() { 
     var shortCommentLen = 9; 
     var comment = $(this).html();     
     $(this).html(shortComment(comment, shortCommentLen)); 
     $(this).toggle(
      function() { $(this).html(comment); }, 
      function() { $(this).html(shortComment(comment, shortCommentLen)); } 
     ); 

     function shortComment(comment, shortCommentLen) { 
      return comment.substring(0, shortCommentLen) + "..."; 
     } 
    }); 
}); 

HTML:

<span class='blah'>this is a long comment to see it all</span> 

toggle(fn1, fn2)功能會交替單擊元素之間的兩個函數之間。