如何将 target="blank" 添加到 Pinboard.in Linkroll 小部件?

How can you add target="blank" to the Pinboard.in Linkroll widget?

我去了 Pinboard's Resource page, got my widget and it all works beautifully. I've styled it up (sidebar on anwarchoukah.com) 并且总体上很开心。

生成的代码是

<script language="javascript" 
  src="http://pinboard.in//widgets/v1/linkroll/?user=Garbad&count=5">
</script>

我的问题是我想在新的 window 中打开链接 - 有什么想法吗?

P.S。我不太擅长 JavaScript

[edit] 第二个答案是行不通的,因为 async. loaded scripts are not allowed to write into the document!但第一个也更短,只有当对 pinboard.in 的请求慢于 500ms 时才会失败。

有效答案

因此,当一段时间过去后,您将走超时路线和 运行 脚本,以确保看板脚本具有 运行 并且其响应可通过 getElementsByTagName 访问。您的 <script 标签将保持原样,您只需在主 .js 文件中添加以下 javascript 代码:

window.onload = function() {
  setTimeout( function() {
    var anchors = document.getElementById( 'pinboard_linkroll' ).getElementsByTagName( 'a' );
    for ( var i = 0; i < anchors.length; i++ ) {
      anchors[i].setAttribute( 'target', '_blank' );
    }
  }, 500 );
};

无效答案留作参考

首先你必须在回调函数中hijack the loading of the script. then you can modify the attr target

这个 javascript 进入你的主脚本加载的地方:

function loadScript( url, callback ) {

  var script = document.createElement( 'script' )
  script.type = 'text/javascript';

  if ( script.readyState ) {  // IE
    script.onreadystatechange = function() {
      if ( script.readyState === 'loaded' || script.readyState === 'complete' ) {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {  // Others
    script.onload = function() {
      callback();
    };
  }

  script.src = url;

  document.getElementById( 'pinboard_hook' )[0].appendChild( script );

}

window.onload = function() {

  loadScript( 'http://pinboard.in//widgets/v1/linkroll/?user=Garbad&count=5', function() {

    var anchors = document.getElementById( 'pinboard_linkroll' ).getElementsByTagName( 'a' );
    for ( var i = 0; i < anchors.length; i++ ) {
      anchors[i].setAttribute( 'target', '_blank' );
    }

  });

}

在您的 html 中,您可以将 <script> 标记替换为简单的包装器,例如:

<span id="pinboard_hook"></span>