setTimeout window.open不能带this.href

时间:2013-09-24 12:05:38

标签: javascript html

我试图在3000ms后打开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()
}

4 个答案:

答案 0 :(得分:1)

(好的,首先,您需要提供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>

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

<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>

答案 1 :(得分:1)

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

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)
}

答案 2 :(得分:0)

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)
}

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

答案 3 :(得分:0)

尝试在字符串外指定href:

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