2008-12-29 66 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)功能会交替单击元素之间的两个函数之间。