javascript - 无法删除附加的 jQuery 元素

标签 javascript jquery html

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

我正在使用 Jquery.dotdotdot 并设法通过阅读更多来删除/添加 chop ,

问题是什么?

当我点击“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: (没关系,只是添加到 fiddle 以提高可见性)

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>");
});

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

最佳答案

您遇到的问题是由于您首先调用了 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: []
        }
    });
});

关于javascript - 无法删除附加的 jQuery 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23366850/

相关文章:

javascript - 保存和加载 div 位置 - 缩放并保存在加载时改变 div 位置

html - 从 iframe 重定向

javascript - 仅在移动设备上全屏覆盖导航

javascript - 根据标准,禁用链接应该设置什么颜色?

java - Thymeleaf SAXParseException : not displaying HTML page

javascript - 将 props 从 redux 映射到组件状态

javascript - 如何使原型(prototype)在对象内的函数内工作?

javascript - 如果 id 不存在,为什么 $ ('#id' ) 返回 true?

javascript - 使用单选按钮填充复选框列表

javascript - HTML5/JavaScript Canvas : Text on Image on Click