【问题标题】:Prevent auto duplicate append html防止自动重复附加 html
【发布时间】:2022-11-24 03:40:54
【问题描述】:

我正在尝试使用类在多个 div 中附加 HTML。但是我的代码在一个部分(HTML 1)中复制了 HTML,而另一个部分是正确的。

HTML 1:

<div class="about-author">
  <div class="author-text">
    This is a author bio. <a href="https://example.com">example</a><a href="https://example.com">example</a>
  </div>
</div>

HTML 2:

<div class="author-info">
  <div class="author-bio">
    This is a author bio. <a href="https://example.com">example</a><a href="https://example.com">example</a>
  </div>
</div>

JavaScript:

$(".about-author .author-text,.author-info .author-bio").each(function () {
    var $this = $(this),
        link = $this.find("a");
    link.each(function () {
        var $this = $(this),
            cls = $this.text().trim(),
            url = $this.attr("href");
        $this.replaceWith('<li class="' + cls + '"><a href="' + url + '" title="' + cls + '" rel="noopener noreferrer" target="_blank"/></li>')
    });
    if (link.length) {
        $this.parent().append('<ul class="author-links social social-color"></ul>');
    }
    $this.find("li").appendTo(".author-links")
});

我想要 HTML 1 和 HTML 2 中的相同输出

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您可以直接循环链接..通过这种方式无需检查长度,因为如果没有在 div 中找到&lt;a&gt;,循环将无法工作

    $(".author-text a,.author-bio a").each(function () {
        var $this = $(this),
        cls = $this.text().trim(),
        url = $this.attr("href");
        $this.replaceWith('<li class="' + cls + '"><a href="' + url + '" title="' + cls + '" rel="noopener noreferrer" target="_blank"/>'+ cls +'</a></li>')
        $this.parent().append('<ul class="author-links social social-color"></ul>');
        $this.find("li").appendTo(".author-links")
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="about-author">
      <div class="author-text">
        This is a author bio 1. 
        <a href="https://example.com">example 1</a>
        <a href="https://example.com">example 2</a>
      </div>
    </div>
    <div class="author-info">
      <div class="author-bio">
        This is a author bio 2. 
        <a href="https://example.com">example 3</a>
        <a href="https://example.com">example 4</a>
        <a href="https://example.com">example 5</a>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 2016-12-11
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      相关资源
      最近更新 更多