【问题标题】:jQuery - How do I add target="_blank" to external links in generated textjQuery - 如何将 target="_blank" 添加到生成文本中的外部链接
【发布时间】:2013-03-29 03:23:17
【问题描述】:

我需要将 target="_blank" 添加到我通常会使用的网站上的所有外部链接:

$("a[href^=http]").each(function(){
    if(this.href.indexOf(location.hostname) == -1) {
        $(this).attr({
            target: "_blank",
            title: "Opens in a new window"
        });
    }
});

不幸的是,我需要检查的链接位于 id 为 messageArea 的 div 中,并且由于它们是通过 ajax 调用生成的,因此它们不会被拾取。

我可以使用 c# 正则表达式函数并重写内容或添加 target="_blank" 但我宁愿让内容保持原始状态。

有什么建议吗?


使用 lucuma 的建议,解决方案是:

$.getJSON(
   "ajax/GetMessage.aspx?message=" + msgID,
   function (msgs) {
       $("div#messageArea").html(msgs.responseText);
       $("div#messageArea a[href^=http]").each(function(){
           if(this.href.indexOf(location.hostname) == -1) {
               $(this).attr({
                   target: "_blank",
                   title: "Opens in a new window"
               });
           }
       });
    }
);

【问题讨论】:

  • 你能把这个函数的调用连接到 ajax.success 事件吗?

标签: jquery


【解决方案1】:

在从 ajax 调用返回时添加以下代码:

$("div#messageArea a[href^=http]").each(function(){
    if(this.href.indexOf(location.hostname) == -1) {
        $(this).attr({
            target: "_blank",
            title: "Opens in a new window"
        });
    }
});

【讨论】:

【解决方案2】:
<a href="http://google.com">google</a>

all is work也许你可以显示更多代码?

【讨论】:

    猜你喜欢
    • 2012-08-16
    • 2011-08-18
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多