【问题标题】:Handling a toggled onclick with JQuery使用 JQuery 处理切换的 onclick
【发布时间】:2008-12-29 12:59:29
【问题描述】:

我有一段文字,我希望显示被截断,但点击后它会展开以显示其余部分。再次单击应该会截断它。

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

但正如您将看到的,它反复调用自己,您必须结束浏览器任务(因此运行此代码时要小心!!!!)

谁能建议为什么会发生这种情况,以及如何解决它。

提前致谢

【问题讨论】:

  • 简短的
  • 好点,但我不认为截断的评论实际上是“缩写”,它会滥用我认为的标签的最纯粹定义,其他人怎么看,这是最纯粹的吗? ?

标签: javascript jquery html


【解决方案1】:

这是因为你在递归调用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 元素时才会执行它。

【讨论】:

  • 当然,非常感谢 Dreas。但是,我刚刚注意到此解决方案存在问题。 JQuery 不会替换绑定事件,它会添加到它,因此每次单击它时都会调用越来越多的函数。使用 DOM 效果很好: document.getElementById("blah").onclick = function() {...};
【解决方案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) 函数在单击元素时在两个函数之间交替。

【讨论】:

  • 是的,当然,在我的解决方案中它还可以,因为它在一个 ajax 驱动的弹出窗口中,所以 JS 对于它的查看是必不可少的,但我喜欢你的选择。
猜你喜欢
  • 2016-03-11
  • 1970-01-01
  • 2023-02-12
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-18
相关资源
最近更新 更多