【问题标题】:Write title content from links with jQuery into DOM after the respective link在相应链接之后将带有 jQ​​uery 的链接中的标题内容写入 DOM
【发布时间】:2021-04-16 11:00:56
【问题描述】:

我将捕获链接标题并将其写在<a href 链接之后,并将其写入span。将链接标记为段落并带有小图标的效果很好(见下图)。

See Example and hover the Icons next to the text

这是我的 DOM 标记:

目前没有问题:

    $( "a.sidenote-icon" ).wrapAll( "<span class='sidenote'><cite class='icon quelle'></cite></span>" );

    var title = $( "a.sidenote-icon" ).attr('title');
    var titlewrap = "<span>" + title + "</span>";
    $( "cite" ).after(titlewrap);

如果我在几种情况下使用 each-function jQuery 将标题添加到一个跨度中,但是三倍 - 因为在我的段落中有三个链接。这是我的每个功能..

$( "a.sidenote-icon" ).each(function() {
    $( this ).wrapAll( "<span class='sidenote'><cite class='icon quelle'></cite></span>" );
    var title = $( this ).attr('title');
    var titlewrap = "<span class='testy'>" + title + "</span>";
    $( "cite" ).after(titlewrap);
});

每个函数都有问题。标题应该只插入一次 - 对于我页面上带有特殊类的每个链接。我的错误在哪里?查看输出

【问题讨论】:

  • 请提供正确的minimal reproducible example 问题。
  • $( "cite" ) 每次选择 all cite 元素,您需要将其限制为正确的元素。
  • 在那个地方试试$( this ).parent().after(titlewrap);
  • 与 next() 或某事。像那样? Ahhh ok 从this 开始并遍历到父级。谢谢!

标签: javascript html jquery each


【解决方案1】:

请查看更新后的example

$( ".frame a.sidenote-icon:first" ).each(function() {
    $( this ).wrapAll( "<span class='sidenote'><cite class='icon quelle'></cite></span>" );

    var title = $( this ).attr('title');
    var titlewrap = "<span class='testy'>" + title + "</span>";
    $( "cite" ).after(titlewrap);

});

您只需要更改如下选择:

$( ".frame a.sidenote-icon:first" ).

【讨论】:

  • 嗨,但我需要所有具有该效果的链接,而不仅仅是第一个。我的问题是,标题在cite-Tag 之后写了三遍。
【解决方案2】:

感谢cBroehttps://codepen.io/mobilat/pen/VwKGxpV

$( "a.sidenote-icon" ).each(function() {
    $( this ).wrapAll( "<span class='sidenote'><cite class='icon quelle'></cite></span>" );

    var title = $( this ).attr('title');
    var titlewrap = "<span class='testy'>" + title + "</span>";
    $( this ).parent().after(titlewrap);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 2012-02-25
    • 2023-04-02
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多