【问题标题】:How to replace a link with another set of links in jQuery?如何用jQuery中的另一组链接替换链接?
【发布时间】:2012-12-14 21:13:28
【问题描述】:

这个问题链接到How can a Greasemonkey script split a link into three related links?

顺便说一下,在给出的答案(有效)中,方法是修改初始链接并将其他链接附加到它。然而,它是为链接到单个 Redmine 问题的提交评论而设计的。我是这么修改的

$('a[title]').each( function () {
    redmineURL = getProjectURL($(this).attr('title'));
});
$("a[href*='/commit/']").each ( function () {
    /*-- Parse each link for the expected format:
        refs #{number} {description text}
    */
    var jThis       = $(this);
    if ($(this).text().match(/#\d+\b/g)) {
        var commitText = $(this).text();
        var cgitURL = $(this).attr('href');
        //$(this).text (commitText[1]);
        $(this).after(processLinkedCommit(redmineURL, commitText, cgitURL)); 
    }
} );

使用此方法,原始链接应替换为函数processLinkedCommit 的输出。 redmineURL 是有问题的Redmine 项目,它是根据页面中的“标题”属性计算得出的。 commitText 是提交的文本,在 Cgit 页面的链接中,cgitURL 是 href 属性。

我想用processLinkedCommit 创建的最多大约 10 个 URL 替换原始链接。看来我将不得不删除 $(this) 并将其替换为 URL 列表,即我必须将它放在它之前的兄弟姐妹之后。我将如何在 jQuery 中做到这一点?

【问题讨论】:

  • 如果您不想帮自己一个忙并使用它,为什么还要打扰 var jThis = $(this);
  • @DavidBarker 已在下面的答案中删除。
  • 事实上它不应该被删除。应该用它代替$(this) 5次以上,5个jQuery对象效率不高。
  • @DavidBarker 我正在探索 Javascript - 了解它是件好事。

标签: javascript jquery jquery-selectors


【解决方案1】:

经过更多思考和查阅文档后,我想出了这个解决方案。替换 URL 使用 .after() 函数附加,原始链接使用 .remove() 函数删除;

$('a[title]').each( function () {
    redmineURL = getProjectURL($(this).attr('title'));
});
$("a[href*='/commit/']").each ( function () {
    if ($(this).text().match(/#\d+\b/g)) {
        var commitText = $(this).text();
        var cgitURL = $(this).attr('href');
        $(this).after(processLinkedCommit(redmineURL, commitText, cgitURL)); 
        $(this).remove();
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多