我去了Pinboard's Resource page ,得到了我的小部件,一切都运行得很好。我已经设计了它的样式(anwarchoukah.com 上的侧边栏)并且总体上很满意。
生成的代码是
<script language="javascript"
src="http://pinboard.in//widgets/v1/linkroll/?user=Garbad&count=5">
</script>
我的问题是我想在新窗口中打开链接 - 有什么想法吗?
附注我不太擅长 JavaScript
最佳答案
[编辑] 第二个答案不起作用,因为 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 。那么你可以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>
关于javascript - 如何将目标 ="blank"添加到 Pinboard.in Linkroll 小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31611286/