You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery实现点击show-more按钮将data-text内图片追加至对应span

当然可行!这完全可以实现

我来给你提供具体的实现方案,不管用原生JavaScript还是jQuery都能搞定,核心就是通过DOM操作读取data-text里的图片HTML,然后插入到目标span中,同时处理按钮的状态切换:

原生JavaScript实现

这个方案不需要依赖任何库,兼容性也很好:

// 给所有的"See more"按钮绑定点击事件
document.querySelectorAll('.show-more').forEach(button => {
  button.addEventListener('click', function() {
    // 找到当前按钮所在的评论span
    const commentSpan = this.closest('.comment-text');
    // 判断当前是展开还是收起状态
    const isExpanded = this.textContent.trim() === commentSpan.dataset.textShortText;

    if (!isExpanded) {
      // 展开:把data-text里的图片HTML插入到span内部的最前面(按钮之前)
      commentSpan.insertAdjacentHTML('afterbegin', commentSpan.dataset.text);
      // 切换按钮文本为"See less"
      this.textContent = commentSpan.dataset.textShortText;
    } else {
      // 收起:删除所有插入的表情图片
      commentSpan.querySelectorAll('.emojioneemoji').forEach(img => img.remove());
      // 切换按钮文本回"See more"
      this.textContent = commentSpan.dataset.textMore;
    }
  });
});

jQuery实现(如果你的项目已经在用jQuery)

如果项目里引入了jQuery,代码可以更简洁:

$('.show-more').on('click', function() {
  const $commentSpan = $(this).closest('.comment-text');
  const isExpanded = $(this).text().trim() === $commentSpan.data('text-short-text');

  if (!isExpanded) {
    // 插入图片HTML到span内按钮之前
    $commentSpan.prepend($commentSpan.data('text'));
    $(this).text($commentSpan.data('text-short-text'));
  } else {
    // 删除表情图片,恢复按钮文本
    $commentSpan.find('.emojioneemoji').remove();
    $(this).text($commentSpan.data('text-more'));
  }
});

注意事项

你提供的HTML里data-text属性的引号没有正确转义(比如alt="鈽�"这种写法会导致HTML解析错误),实际使用时要把data-text里的引号转成",比如:

<span class="comment-text" data-text="&lt;img alt=&quot;鈽�&quot; class=&quot;emojioneemoji&quot; src=&quot;https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.7/assets/png/263a.png&quot;&gt;..." ...>
  <a class="show-more">See more</a>
</span>

这样JavaScript才能正确读取到完整的图片HTML内容。

内容的提问来源于stack exchange,提问作者Faizal Munna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:07:53