setTimeout window.open 不能接受这个.href

setTimeout window.open can't take this.href

本文关键字:href 不能接受 window open setTimeout      更新时间:2023-09-26

我试图在 3000 毫秒后打开 href onMouseOver。但它只是弹出一个空白窗口。我错过了什么?

.HTML:

<a href="../cc2b/myrec.html" onMouseOver="Popup = setTimeout('openwindow(this.href)',3000);" onMouseOut="clearInterval(Popup)">My Rec</a>

JavaScript:

var Popup = null;
function openwindow()
{
    var win = window.open()
}

(好的,首先,你需要提供一个 URL 到 window.open() ,否则它不知道要打开到哪个页面。 除此之外:)

执行setTimeout()时,延迟代码中的 this 值将重置。

快速解决方法是立即提取 URL,然后将函数传递到可以使用该变量的setTimeout()中。

<a href="../cc2b/myrec.html"
        onMouseOver="var popupUrl = this.href; Popup = setTimeout(function(){openwindow(popupUrl)}), 3000);"
        onMouseOut="clearInterval(Popup)">
    My Rec
</a>

但是,一个更简洁的解决方案是通过在openhoverpopup函数中设置超时来最小化onMouseOver中的代码:

<a href="../cc2b/myrec.html"
        onMouseOver="openhoverpopup(this.href)"
        onMouseOut="clearhoverpopup()">
    My Rec
</a>
<script>
    var popupTimeout = null;
    function openhoverpopup(url) {
        popupTimeout = setTimeout(function () {
            window.open(url);
        }, 3000);
    }
    function clearhoverpopup() {
        clearTimeout(popupTimeout);
    }
</script>

对于较旧的 IE 浏览器,您可以使用 event.targetevent.srcElement 从触发鼠标悬停事件的元素中获取 URL。

http://jsfiddle.net/b42pr/1

.HTML

<a href="theURL" onmouseover="popURL()">Hover</a>

JavaScript

function popURL() {
    var url = event.target.href || event.srcElement.href;
    console.log("Open URL: " + url);
    setTimeout(function(){
        window.open(url);
    }, 3000)
}

this.href是未定义的,我认为您正在寻找window.location.href

> this.href
  undefined
> window.location.href
  "http://stackoverflow.com/questions/18981172/settimeout-window-open-cant-take-this-href"

另外,您的函数

function openwindow()
{
    var win = window.open()
}

不带任何参数,也不打开任何内容。将其更改为

function openwindow(target)
{
    var win = window.open(target)
}

但要小心,大多数弹出窗口阻止程序会阻止这种窗口。

尝试在字符串之外指定 href:

<a href="../cc2b/myrec.html" onMouseOver="Popup = setTimeout('openwindow(' + window.location.href + ')',3000);" onMouseOut="clearInterval(Popup)">My Rec</a>