我正在尝试制作一个脚本(用于Greasemonkey)(访问特定页面时),
如果您单击我插入到页面中
的链接(该链接“什么都不做”,即我使用event.preventDefault();
)
以打开页面中的所有链接在新标签页中,
但每个标签页之间都存在延迟,例如 500毫秒
我有此代码(基于此答案)
var z = ($('table td').find('a')); // selection via jQuery
$("#mylink").on('click', function(event){
event.preventDefault();
var $this = $(this);
for (i=0; i<z.length; i++) {
window.open(z[i].href, '_blank');
}
});
上面的方法有效,但是同时打开所有链接。
因此,我尝试将window.open
行包含在以下任一行中:
setInterval(function() {
window.open(z[i].href, '_blank');
}, 500);
或者:
setInterval("window.open('"+z[i].href+"','_blank')", 500);
但无济于事:两者均无济于事,而且TypeError: z[i] is undefined
当我单击链接时,我在浏览器控制台中仅遇到连续错误。
对于它的价值,如果它是链接的事实是导致问题的原因,那么
我还有用于创建按钮而不是链接的代码:
var z = ($('table td').find('a')); // selection via jQuery
var button = document.createElement("button");
button.id = 'mybutton';
button.type = "button";
button.value = "im a button";
context.appendChild(button);
$("#mybutton").on('click', function(event){
event.preventDefault();
var $this = $(this);
for (i=0; i<z.length; i++) {
window.open(z[i].href, '_blank');
}
});
window.open
以上述两种方式中的任何一种方式更改行都无济于事,
并且在Browser Console中也遇到相同的错误。
首先,您正在使用jQuery。为什么不充分利用它呢?除了使用for
循环之外,您还可以使用$.each()
jQuery方法。另外,setInterval()
您应该使用而不是来使用setTimeout()
该用例。以下对我有用。
var z = ($('table td').find('a')); // selection via jQuery
$("#mylink").on('click', function(event){
event.preventDefault();
var $this = $(this);
var interval = 0; //set the starting point for the timeout interval
z.each(function() {
var href = $(this).attr('href');
setTimeout(function() {
window.open(href, '_blank');
}, interval);
interval += 1500; //up the interval to ensure a delay between opening
});
});
旁注,我希望用户期望此功能,因为这可能会令人讨厌。另外,大多数现代浏览器都会阻止这些弹出窗口。只是我的两分钱。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句