【问题标题】:jQuery remove class on .clickjQuery删除.click上的类
【发布时间】:2010-08-13 14:47:20
【问题描述】:

这是我的html:

<a href="#">Read more</a>

<div class="moreDetails">
  <p class="additionalText">Some text help here, random length.</p>
  <p class="author">
    <span class="bolder"><a href="minidashboard.php?user_url=http://url.people/1332517">Name</a>
    </span>
  </p>
<div class="replies">
  <span>
    <a href="topic.php?id=http://url/topics/1049198">1</a>
  </span>
</div>

然后,当 .additionalText 的文本长度超过 36 个字符时,我会使用 jQuery 向 div 添加一个类。

jQuery:

$('.moreDetails p.additionalText').filter(function () {
  if ($(this).text().length > 32) {
    $(this).addClass('trim');
  }
});

我现在想要的是当&lt;a href="#"&gt;Read more&lt;/a&gt; 被点击类.trim 被删除并显示内容。

.trim 将段落设置为固定高度,溢出设置为隐藏。

【问题讨论】:

  • 仅供参考,我并不是说您的代码不起作用,但.filter() 的使用有点奇怪。您可能想改用.each()。或者使用.filter() 做更多这样的事情:$('.moreDetails p.additionalText').filter(function () { return $(this).text().length &gt; 32; }).addClass('trim');

标签: jquery


【解决方案1】:

你可以给那个链接一个类,像这样:

<a class="readMore" href="#">Read more</a>

然后添加一个点击处理程序,像这样:

$("a.readMore").click(function() {
  $(this).next().find('.additionalText').removeClass('trim');
});

这可以通过.next().find() 找到相对于&lt;a&gt;&lt;div&gt;。如果&lt;div&gt; 没有立即 跟随&lt;a&gt; 就像在您发布的代码中一样,这可能需要一些调整,例如,如果中间有元素但它们仍然是您想要的兄弟姐妹需要.nextAll('.moreDetails:first') 而不是.next()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多