目标空白不起作用?

Target Blank Not Working?

我正在尝试使用 jQuery 中的 "attr" 功能在新的 window 中打开 links,但没有成功。

这是客户站点:http://www.sunsetstudiosent.com 在 "News" 部分工作。

此外,是否有办法区分并仅将其应用于 link 场外 link?

  <script>
     var sBlock = $('[data-block-json*="9dac9e62587eab820575"]'),
         items = sBlock.find('.summary-item');  
     $.each(items, function() { 
       var $this = $(this),
           itemLink = $this.find('.summary-title a').attr('href');
       $this.find('.summary-read-more-link').attr('href', itemLink);
       $this.find('.summary-metadata-item a').attr('href', itemLink);
       $(this).attr('target', '_blank');
     });
  </script>

一行香草 Javascript 会为你做;不需要 jQuery:

document.querySelectorAll('#block-8c94657a90c2362b8126 .summary-title-link')
    .forEach(function(x) {
        x.setAttribute('target', '_blank');
    });

在应用 target="_blank" 之前还会检查 link 是否在同一域中的类似代码:

document.querySelectorAll('#block-8c94657a90c2362b8126 .summary-title-link')
    .forEach(function(x) {
        var url = new URL(x.href);
        if (url.host !== window.location.host) {
            x.setAttribute('target', '_blank');
        }
    });

如果您不确定是否会添加这些元素上的 link,您可能希望将函数体包装在 try-catch 块中。

因为 $(this) 持有 .summary-item 而不是锚标签...

因此 $(this).attr('target', '_blank') 会将 target 属性添加到 .summary-item 而不是其 <a> 标签...

因此您需要更改此处的逻辑...尝试在此处使用 find() jQuery

$(this).find("a").attr('target', '_blank');

所以你的完整代码将是

var sBlock = $('[data-block-json*="9dac9e62587eab820575"]'),
  items = sBlock.find('.summary-item');
$.each(items, function() {
  var $this = $(this),
    itemLink = $this.find('.summary-title a').attr('href');
  $this.find('.summary-read-more-link').attr('href', itemLink);
  $this.find('.summary-metadata-item a').attr('href', itemLink);
  $(this).find("a").attr('target', '_blank');
});