必须等待执行 jQuery 直到服务加载完毕

Have to wait to execute jQuery till the service is loaded

我正在尝试在新选项卡中打开超链接。为了在新选项卡中加载,我使用以下代码,它将 运行 一次并在锚标记中添加 target="_blank" :

<script>
    $(document).ready(function(){
        alert("ready");
        $("a", "#myCustomContent").each(function() {
            $(this).attr('target', '_blank');
        });
    }); 
</script>

但是 jQuery 是在从服务调用检索内容之前执行的,我无法在新选项卡中打开超链接,因此我尝试使用以下代码:

$(window).bind("load", function() {
   $("a", "#myCustomContent").each(function() {
       $(this).attr('target', '_blank');
   });
});

这里加载失败是因为部分图片或文件加载失败,还是需要更多时间?

我需要找到一种方法来调用 jQuery 以在新选项卡中打开 "ahref" 标签。

试试这个。也许这会解决问题

$(document).click(function(e){
    if($(e.target).parents('#myCustomContent').size() && e.target.tagName=="A"){
        e.preventDefault();
        window.open(e.target.href);
        }
      })

如果没有看到更多的代码,我将很难准确地破译最佳步骤是什么,但听起来您在代码运行后加载了带有链接的图像。您总是可以尝试在加载时更新点击处理程序的方法:

$('body').on('click', 'a', function(){
    $(this).attr('target', '_blank');
});

或者您可以查看一个函数来检查您的图像是否已加载并设置超时,直到它们全部设置完毕。

var changeTarget = function() {
    if ($('body').find('#img')) {
        //do code it's loaded
    } else {
        //repeat in 100 miliseconds
        setTimeout(changeText,100);
    }
}
changeTarget();

下面的代码可以很好地在新标签页中打开 hyperlink。

如果页面中只有某些锚标签(hyperlinks)需要在新的window中打开,那么可以使用下面的代码

$(document).click(function(e){
    if($(e.target).parents('#myCustomContent').size() && e.target.tagName=="A"){
        e.preventDefault();
        window.open(e.target.href);
        }
      });

其中 "myCustomContent" 是分配给部门的 ID 或

标签,其中存在超级 link。

如果页面中的所有锚标记都必须在新标签页中打开,则可以使用以下代码。

$('body').on('click', 'a', function(){
    $(this).attr('target', '_blank');
});

感谢@JeremyS 和@doniyor 的帮助