无法删除附加的jQuery元素

时间:2014-04-29 13:59:37

标签: javascript jquery html

注意:这看起来类似于我之前发布的问题,但是关于另一个问题。

我正在使用Jquery.dotdotdot并设法使用Read More删除/添加截断,

有什么问题?

当我点击"Read More"时,它会展开内容,当我点击"Read Less"时,它会隐藏展开的内容。如果我再次点击"Read More",您会发现"Read Less"链接未被删除,并且已添加了另一个链接(它应该这样做)。

JSFiddle:

Live Website:

HTML:

<div class='article'>
<div class='articleheader'>Title</div>
<div id='article_$count' class='articlecontent'>
    <p>long content goes here
    </p>
</div>
</div>

CSS: (无所谓,只是为了提高能见度而添加到小提琴中)

jQuery的:

/*Adds the "Read More" link and truncates the text when clicking read Less. */
$(".article").on('click', '.readless', function () {
$(this).parents('div').eq(0).dotdotdot({
    ellipsis: '... ',
    wrap: 'word',
    fallbackToLetter: true,
    after: '<a href="#" class="readmore">Read more &raquo;</a>',
    watch: false,
    height: 100,
    tolerance: 10,
    lastCharacter: {
        remove: [' ', ',', ';', '.', '!', '?'],
        noEllipsis: []
    }
});
$('.article').find('.readless').remove(); /*THIS IS WHAT DOESN'T WORK*/
});

/*Truncates all articles */
$("[id^=article]").dotdotdot({
ellipsis: '... ',
wrap: 'word',
fallbackToLetter: true,
after: '<a href="#" class="readmore">Read more &raquo;</a>',
watch: false,
height: 100,
tolerance: 10,
lastCharacter: {
    remove: [' ', ',', ';', '.', '!', '?'],
    noEllipsis: []
}
});


/*removes truncation and appends "Read Less" link to content*/
$(".article").on('click', '.readmore', function () {
$(this).parents('div').eq(0).trigger("destroy").append("<a href='#' class='readless'>Read Less &raquo;</a>");
});

感谢任何帮助。谢谢。 :)

1 个答案:

答案 0 :(得分:2)

您遇到的问题是由您首次调用dotdotdot插件然后尝试删除read less链接引起的。此时DOM已经被更新,因此链接不再可访问(但它仍然存储在内存中,这就是之后它再次出现的原因)。

因此,您需要拆分删除链接和调用插件,如下所示:

$(".article").on('click', '.readless', function () {
    var parent = $(this).parents('div').eq(0);
    $(this).remove(); 
    parent.dotdotdot({
        ellipsis: '... ',
        wrap: 'word',
        fallbackToLetter: true,
        after: '<a href="#" class="readmore">Read more &raquo;</a>',
        watch: false,
        height: 100,
        tolerance: 10,
        lastCharacter: {
            remove: [' ', ',', ';', '.', '!', '?'],
            noEllipsis: []
        }
    });
});
相关问题