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

Have to wait to execute jQuery till the service is loaded

本文关键字:加载 服务 jQuery 等待 执行      更新时间:2023-09-26

我正在尝试在新选项卡中打开超链接。为了加载新选项卡,我使用以下代码,它将运行一次并在锚标签中添加 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();

下面的代码适用于在新选项卡中打开超链接。

如果只需要在新窗口中打开页面中的某些锚标签(超链接),则可以使用以下代码

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

其中"myCustomContent"是提供给存在超链接的部门或

标记的 ID。

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

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

感谢您的帮助,@JeremyS和@doniyor