【问题标题】:Onclick Only seems to be working onceOnclick Only 似乎只工作一次
【发布时间】:2014-04-29 11:56:59
【问题描述】:

所以,我遇到了这个问题,过去几天我一直在尝试解决它,但没有成功。我正在使用 Jquery.dotdotdot

有什么问题?

点击"Read More"时会展开内容,点击"Read Less"时会隐藏展开的内容。如果我点击"Read More" SECOND 次,它将不起作用。

JSFiddle:

Live Website:

HTML:

<div class='article'>
<div class='articleheader'>Title</div>
<div id='article_$count' class='articlecontent'>
    <p>But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure? On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee
       <a href='#' class='readless'>Read Less</a>
    </p>
</div>
</div>

CSS: (没关系,只是添加到小提琴以提高可见性)

jQuery:

/*Adds the "Read More" link and truncates the text when clicking read Less. */
$('.readless').click(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: []
    }
});
});

/*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 shows the hidden "Read Less" link in content*/
$('.readmore').click(function () {
    $(this).parents('div').eq(0).trigger("destroy");
});

【问题讨论】:

标签: javascript jquery html jquery-plugins


【解决方案1】:

事件处理程序仅绑定到当前选定的元素;在您的代码进行事件绑定调用时,它们必须存在于页面上。

由于readmore anchor是动态创建的,你需要使用Event Delegation。您必须使用委托事件方法使用.on()

使用

/*removes truncation and shows the hidden "Read Less" link in content*/
$(".article").on('click', '.readmore', function () {
    $(this).parents('div').eq(0).trigger("destroy");
});

DEMO

【讨论】:

  • 哇,这太完美了。我是 JS/jQuery 的新手,所以这对我有很大帮助! :) 我会尽快接受!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 2011-04-05
相关资源
最近更新 更多