代码之家  ›  专栏  ›  技术社区  ›  Dan

使用JQuery处理切换的onclick

  •  1
  • Dan  · 技术社区  · 17 年前

    我试图使用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>
    

    有人能提出为什么会发生这种情况,以及如何解决它吗。

    提前谢谢

    2 回复  |  直到 17 年前
        1
  •  3
  •   Powerlord    17 年前

    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

        2
  •  2
  •   foxy    17 年前

    未启用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) 单击元素时,函数在两个函数之间交替启用。